1

I don't understand why concatMap, rather than simply map, is needed in this:

expand :: [[Int]] -> [[Int]]

expand xs = concatMap (\a -> (map (\b -> a++b) [[1],[2],[3]])) xs

don't a and b each pick up just a simple list in their respective assignments, so that a++b as the concatenation of these lists should be just another list?

Would appreciate some insight ...

2
  • What are you trying to do? It would help if you gave an example of an input and expected output. Commented Nov 9, 2014 at 18:57
  • It looks as you are correct, both a and b have type [Int]. Can you clarify the actual question? It's hard to answer this. If you don't understand, try to rewrite concatMap f xs as concat (map f xs). You will find that the outermost map is producing [[[Int]]]. Commented Nov 9, 2014 at 19:15

1 Answer 1

1

map preserves the number of elements in the input list, so you can't only use that since you want to create three elements in the output for every list in the input list. concatMap allows you to do that by returning a list to be incorporated into the output list. The inner map creates those three lists for the input list, but since it returns a list of lists for each input list you need to remove the extra layer of nesting.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks -- that comment that the number of elements in the input list must be conserved, whereas my function multiplies it by three, makes it clear why a list of lists must be returned by the inner map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.