Search code examples
haskellfunctorapplicative

Haskell: fmap on nested functors


What is the way to abstract mapping a function over a list of functors?

I understand the basic applicative

λ: [(+2),(*2)] <*> [10,20]
[12,22,20,40]

but how do I handle [(+2),(*2)] ???? [Just 10, Just 20]?

all the ways I can think of seem really convoluted.

for example:

λ: (<$>) <$> [(+2),(*2)]  <*> [Just 10, Just 20]
[Just 12,Just 22,Just 20,Just 40]

Solution

  • You can use Data.Functor.Compose to treat nested Functors/Applicatives as a single Functor/Applicative:

    ghci> import Data.Functor.Compose
    ghci> getCompose (Compose [pure (+2), pure (*2)] <*> Compose [Just 10, Just 20])
    [Just 12,Just 22,Just 20,Just 40]
    

    But perhaps the (Compose, getCompose) newtype noise is not worth it in this case.