Search code examples
haskellfunctional-programmingfunctor

Confused about (fmap length Just) [1,1,1,1] vs. fmap length $ Just [1,1,1,1]


I understand that the parens force a different order of operations, but I don't quite understand the first result:

>> (fmap length Just) [1, 2, 3]
1

Whereas the following makes perfect sense - we are lifting the length function over the Just structure, so we should get "Just [length of list]":

>> fmap length $ Just [1, 2, 3]
Just 3

What's going on in the first case?


Solution

  • In the first case, you are getting the function instance of Functor, for which fmap = (.), so:

    fmap length Just [1,2,3]
    =
    (length . Just) [1,2,3]
    =
    length (Just [1,2,3])
    

    The Foldable instance for Maybe says that Nothings have a length of 0 and Justs have a length of 1 -- which is quite sensible if you think of Maybe a as a bit like a collection of as that has at most one a in it.