Reputation: 4142
This is a trival question.
But what is the standard way to map a function (+1
in this example) on nested list?
map (\x -> map (+1) x) [[1,2,3],[4,5,6]]
I use the above way in my code, but what is a good way to do that? Is there something like a mapNested (+1) [[1,2,3],[4,5,6]]
or similar? I used google and hoogle but got too much generic results.
Upvotes: 13
Views: 6073
Reputation: 11372
I don't think it defined anywhere in the standard library, but you can define it as such:
mapNested :: (a -> b) -> [[a]] -> [[b]]
mapNested = map . map
Or to make it more generic (ie. work on other functors than lists):
fmapNested :: (Functor f, Functor g) => (a -> b) -> f (g a) -> f (g b)
fmapNested = fmap . fmap
Example use:
fmapNested (+1) [Some 1, None, Some 3] -- == [Some 2, None, Some 4]
Upvotes: 17
Reputation: 137997
There's a few ways but the most obvious is:
Prelude> map (map (+1)) [[1,2,3],[4,5,6]]
[[2,3,4],[5,6,7]]
This would be the textbook answer.
Maybe you like to do the outer part with a list comprehension?
Prelude> [ map (+1) xs | xs <- [[1,2,3],[4,5,6]] ]
[[2,3,4],[5,6,7]]
Or even the whole thing?
Prelude> [ [ x + 1 | x <- xs ] | xs <- [[1,2,3],[4,5,6]] ]
[[2,3,4],[5,6,7]]
Upvotes: 20