Fork me on GitHub

monads in haskell part 2

The Either monad is a kind of extension to the Maybe monad. Instead of having one type, the Either monad has two types. That brings more flexibility over the Maybe monad because we can tell what actually went wrong with a calculation.

The Either monad is defined as follows:

data Either = Left a | Right b

So a value of the Either type contains either a value of type a or type b. The two constructors are Left and Right with underlying assumption that Left is an error and Right is, well, right. So Left a is usually a string that tells us what went wrong and Right is the resulting value that was checked. Either is mostly used in error handling. Here is an example:

zerodiv :: Float -> Float -> Either String Float
zerodiv a b
     | b==0 = Left "division by zero is not defined"
     | otherwise = Right (a/b)

Here we return a string when our float is divided by zero, i.e an error message. Chaining here can be done with a lambda function:

>>> zerodiv 10 0 >>= \x -> return x
>>> Left "division by zero is not defined"
>>> zerodiv 10 2 >>= \x -> return x
>>> Right 5.0

But we cannot chain zerodiv with another zerodiv because it requires two arguments and (>>=) is defined with one argument on the right side:

>>> :t (>>=)
>>> (>>=) :: Monad m => m a -> (a -> m b) -> m b

There is more to say about either here and a little bit in the real world haskell site. Also, the documentation can be useful.

Comments !