Stéphane Laurent
Stéphane Laurent

Reputation: 84519

Changing the type of the elements in a nested list

I have the object tableaux :: [[[Int]]] and I want to change it to [[[Int32]]]. I do:

int32ToInt :: Int32 -> Int
int32ToInt = fromIntegral

tableaux32 = map (\y -> map (\x -> map intToInt32 x) y) tableaux

Is there a better way?

Upvotes: 0

Views: 118

Answers (2)

Markus1189
Markus1189

Reputation: 2869

While in this example you can get away with a simple chain of maps, whenever you have deeply nested structures you should reach for lenses. There are multiple packages for that in Haskell, one of the most powerful is Edward Kmett's lens.

With lens you can use for example traverse to focus each element of a Traversable container:

convert :: (a -> b) -> [[[a]]] -> [[[b]]]
convert = over (traverse . traverse . traverse)

The power of lens is that you can also have a [Vector [Maybe a]] instead and the same function convert will still work after generalizing the type signature.

As Daniel Wagner noted in the comments you can still do the above example by using only fmap. The intention was to highlight that lens generalizes this pattern of modifying nested structures very nicely and should be preferred once those modifications get more complicated.

Upvotes: 0

amalloy
amalloy

Reputation: 91837

Consider that (\x -> map f x) is simply map f. How many times do you see this pattern in your function? I see it twice.

Upvotes: 6

Related Questions