I'm new to Haskell. In the Monad docs, there is an example use for the void function:
>>> void (Left 8675309)
Left 8675309
>>> void (Right 8675309)
Right ()
I'm having a tough time figuring out why this is the case.
I see that void is defined as: void x = () <$ x
and (<$) = fmap . const
but I cannot figure out why there is a difference between Left and Right.
Any hints?
Because fmap
maps the value defined in the Right
, not in the Left
. Indeed, Either
is defined as:
data Either a b = Left a | Right b
and the Functor
of Either a
is thus implemented as:
instance Functor (Either a) where
fmap _ (Left x) = Left x
fmap f (Right x) = Right (f x)
This makes sense, since the Functor
expects a type of kind * -> *
, and thus the fmap :: Functor f => (b -> c) -> f b -> f c
makes a mapping for Either
with fmap :: (b -> c) -> Either a b -> Either a c
.
Since void
is defined as void = fmap (const ())
, this thus means that if we make an analysis per case, we see:
fmap (const ()) (Left x) = Left x
fmap (const ()) (Right x) = Right (const () x) = Right ()