views:

285

answers:

3

So, for example, say I had a list of numbers and I wanted to create a list that contained each number multiplied by 2 and 3. Is there any way to do something like the following, but get back a single list of numbers instead of a list of lists of numbers?

mult_nums = [ [(n*2),(n*3)] | n <- [1..5]] 
-- this returns [[2,3],[4,6],[6,9],[8,12],[10,15]]
-- but we want [2,3,4,6,6,9,8,12,10,15]
+13  A: 

you could use concat.

concat [ [(n*2),(n*3)] | n <- [1..5]] 
output: [2,3,4,6,6,9,8,12,10,15]
vili
+4  A: 

In some similar cases concatMap can also be convenient, though here it doesn't change much:

concatMap (\n -> [n*2,n*3]) [1..5]
FunctorSalad
For `instance Monad []`, `(>>=) == flip concatMap`... it seems that Chris's answer glossed over that part, but this answer is a subset of the one above.
ephemient
+14  A: 
Chris Conway