The either type provides another implementation of optional values, generally used to represent computations that can fail. However, it augments just and nothing by allowing the kind of failure to be annotated. When a computation results in nothing , it clearly failed, but it is not always clear why (especially after a long chain of monadic computation).
The success constructor is exactly like just —it signals a successful value, and it can be mapped over as a functor or applicative functor and sequenced as a monad. The failure constructor has the same short-circuiting behavior of nothing , but it accepts a value like success , which can be used to annotate the kind of failure.
As an example, we can rewrite the safe- functions from the maybe section using either.
(safe-/ab)))> (divide-first-two'(2011))(success 20/11)
> (divide-first-two'(30))(failure "attempted to divide by zero")
> (divide-first-two'(3))(failure "attempted to get the first element of an empty list")
(success 'hello)
(failure 'failed)
Either values are monads that short-circuit on failure .
(success 2)
(failure 'failed)
(success 3)
(success 2)
either-value:maybe?
6
2
3
procedure
( from-success default-valueeither-value)→any/c
default-value:any/ceither-value:either?
#f
18
procedure
( from-failure default-valueeither-value)→any/c
default-value:any/ceither-value:either?
"failed"
#f
procedure
( from-either either-value)→any/c
either-value:either?
"failed"
18
(success 1)
(failure "failed")
procedure
( flip-either e)→either?
e:either?
(failure 'foo)
(success 'bar)
procedure
( maybe->either xm)→either?
x:any/cm:maybe?
(success 42)
(failure 'fail)
procedure
( either->maybe e)→maybe?
e:either?
(just 42)
#<nothing>