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?
The expression fmap (*2) is a function that takes a functor f over numbers and returns a functor over numbers. That functor can be a list, a Maybe , an Either String, whatever. The expression fmap (replicate 3) will take a functor over any type and return a functor over a list of elements of that type.
fmap is used to apply a function of type (a -> b) to a value of type f a , where f is a functor, to produce a value of type f b . Note that for any type constructor with more than one parameter (e.g., Either ), only the last type parameter can be modified with fmap (e.g., b in `Either a b`).
Functors and monoids were both wrappers around a value that allow us to execute operations on them. In the case of functors it was map in the case of monoids it was compose , where compose is a single operation. Now monads. Monad's are both a functor and a monoid.
Another simple example of a functor is the Maybe type. This object can contain a value of a particular type as Just , or it is Nothing (like a null value).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With