Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Left and Right

Tags:

haskell

I am currently reading the excellent "Learn You a Haskell for Great Good", and in the section about functors there is an example involving Either which I don't understand:

ghci> fmap (replicate 3) (Right "blah")
Right ["blah","blah","blah"]
ghci> fmap (replicate 3) (Left "foo")
Left "foo"

Why is the latter not Left ["foo", "foo", "foo"]?

like image 786
mkrieger1 Avatar asked Mar 01 '15 23:03

mkrieger1


1 Answers

The Left constructor on Either is implemented as the "failure case". Like other functors, once this failure value enters the equation, it prevents any real computations from happening. So, when you apply fmap to Left "foo" it immediately returns the same "failure" value.

You can see this by looking at how Either implements fmap:

instance Functor (Either a) where
    fmap f (Right x) = Right (f x)
    fmap f (Left x) = Left x

The idea here is that Left "foo" would actually be something more descriptive, like Left "Value could not be computed". If you try to apply further functions to that value, you just want the "error" to get passed along intact.

If it helps, just imagine how fmap would work on some other type where the failure case is more obvious, e.g.:

-- Maybe: failure value is `Nothing`
fmap (replicate 3) (Nothing)

This produces Nothing, not [Nothing, Nothing, Nothing]

like image 194
Michael Edenfield Avatar answered Nov 03 '22 18:11

Michael Edenfield