mrsteve
mrsteve

Reputation: 4142

How to map a function on the elements of a nested list

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

Answers (3)

arrowd
arrowd

Reputation: 34421

You need composition of maps: (map . map) (+1) [[1,2,3],[4,5,6]]

Upvotes: 5

Tarmil
Tarmil

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

Don Stewart
Don Stewart

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

Related Questions