2
User
Recs.
Recs.
3
Updates
Last
Updated
Updated
Activity
9 Options
The following are equivalent:
concat $ map f list
concatMap f list
list >>= f
Edit
Since more details were requested...
concat :: [[a]] -> [a]
'concat' takes a list of lists and concatenates them into a single list.
map :: (a -> b) -> [a] -> [b]
'map' maps a function over a list.
concatMap :: (a -> [b]) -> [a] -> [b]
'concatMap' is equivalent to '(.) concat . map:' map a function over a list, and concatenate the results.
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
A 'Monad' has a bind operation, which is called' >>=' in Haskell (or its sugared 'do'-equivalent). List, aka '[]', is a 'Monad'. If we substitute '[]' for 'm' in the above:
instance Monad [] where
(>>=) :: [a] -> (a -> [b]) -> [b]
return :: a -> [a]
What's the natural thing for the 'Monad' operations to do on a list? We have to satisfy the monad laws,
return a >>= f == f a
ma >>= (\a -> return a) == ma
(ma >>= f) >>= g == ma >>= (\a -> f a >>= g)
You can verify that these laws hold if we use the implementation
instance Monad [] where
(>>=) = concatMap
return = (:[])
return a >>= f == [a] >>= f == concatMap f [a] == f a
ma >>= (\a -> return a) == concatMap (\a -> [a]) ma == ma
(ma >>= f) >>= g == concatMap g (concatMap f ma) == concatMap
(concatMap g . f) ma == ma >>= (\a -> f a >>= g)
This is, in fact, the behavior of 'Monad []'. As a demonstration,
double x = [x,x]
main = do
print $ map double [1,2,3]
-- [[1,1],[2,2],[3,3]]
print . concat $ map double [1,2,3]
-- [1,1,2,2,3,3]
print $ concatMap double [1,2,3]
-- [1,1,2,2,3,3]
print $ [1,2,3] >>= double
-- [1,1,2,2,3,3]
Specs
Pros
Know any positive aspects of this option?
Cons
Know any negative aspects of this option?
Recommendations
Shorthand for a common list operation
Recommended 11 years ago
Graham hasn’t added their experience, pros or cons to their recommendation.
Shorthand for a common list operation
Recommended 11 years ago
T-R hasn’t added their experience, pros or cons to their recommendation.