Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 419
AgentLiquid Avatar asked Mar 05 '18 04:03

AgentLiquid


People also ask

Is Fmap a functor?

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.

What does Fmap do Haskell?

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`).

Are functors Monoids?

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.

Is maybe a functor Haskell?

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).


1 Answers

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.

like image 120
Daniel Wagner Avatar answered Nov 05 '22 20:11

Daniel Wagner