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?
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 Nothing
s have a length of 0
and Just
s have a length of 1
-- which is quite sensible if you think of Maybe a
as a bit like a collection of a
s that has at most one a
in it.