2013-01-09 10:07:46 +00:00
|
|
|
|
2013-03-10 08:54:37 +00:00
|
|
|
module Either where
|
|
|
|
|
2013-03-11 05:42:57 +00:00
|
|
|
import List
|
2013-03-10 08:54:37 +00:00
|
|
|
|
2013-03-24 12:45:56 +00:00
|
|
|
-- Represents any data that can take two different types.
|
|
|
|
--
|
|
|
|
-- This can also be used for error handling `(Either String a)` where error
|
2013-05-24 08:47:15 +00:00
|
|
|
-- messages are stored on the left, and the correct values (“right”
|
|
|
|
-- values) are stored on the right.
|
2013-01-09 10:07:46 +00:00
|
|
|
data Either a b = Left a | Right b
|
|
|
|
|
2013-03-24 12:45:56 +00:00
|
|
|
-- Apply the first function to a `Left` and the second function to a `Right`.
|
|
|
|
-- This allows the extraction of a value from an `Either`.
|
2013-02-07 18:54:21 +00:00
|
|
|
either : (a -> c) -> (b -> c) -> Either a b -> c
|
2013-01-09 10:07:46 +00:00
|
|
|
either f g e = case e of { Left x -> f x ; Right y -> g y }
|
|
|
|
|
2013-03-24 12:45:56 +00:00
|
|
|
-- True if the value is a `Left`.
|
2013-03-11 05:42:57 +00:00
|
|
|
isLeft : Either a b -> Bool
|
|
|
|
isLeft e = case e of { Left _ -> True ; _ -> False }
|
2013-02-07 18:54:21 +00:00
|
|
|
|
2013-03-24 12:45:56 +00:00
|
|
|
-- True if the value is a `Right`.
|
2013-02-07 18:54:21 +00:00
|
|
|
isRight : Either a b -> Bool
|
2013-01-09 10:07:46 +00:00
|
|
|
isRight e = case e of { Right _ -> True ; _ -> False }
|
|
|
|
|
2013-03-24 12:45:56 +00:00
|
|
|
-- Keep only the values held in `Left` values.
|
2013-04-22 09:36:11 +00:00
|
|
|
lefts : [Either a b] -> [a]
|
2013-05-06 09:30:50 +00:00
|
|
|
lefts es = List.foldr consLeft [] es
|
2013-02-07 18:54:21 +00:00
|
|
|
|
2013-03-24 12:45:56 +00:00
|
|
|
-- Keep only the values held in `Right` values.
|
2013-04-22 09:36:11 +00:00
|
|
|
rights : [Either a b] -> [b]
|
2013-05-06 09:30:50 +00:00
|
|
|
rights es = List.foldr consRight [] es
|
2013-01-09 10:07:46 +00:00
|
|
|
|
2013-03-24 12:45:56 +00:00
|
|
|
-- Split into two lists, lefts on the left and rights on the right. So we
|
|
|
|
-- have the equivalence: `(partition es == (lefts es, rights es))`
|
2013-04-22 09:36:11 +00:00
|
|
|
partition : [Either a b] -> ([a],[b])
|
2013-05-06 09:30:50 +00:00
|
|
|
partition es = List.foldr consEither ([],[]) es
|
|
|
|
|
|
|
|
consLeft e vs =
|
|
|
|
case e of
|
|
|
|
Left v -> v::vs
|
|
|
|
Right _ -> vs
|
|
|
|
|
|
|
|
consRight e vs =
|
|
|
|
case e of
|
|
|
|
Left _ -> vs
|
|
|
|
Right v -> v::vs
|
|
|
|
|
|
|
|
consEither e (ls,rs) =
|
|
|
|
case e of
|
|
|
|
Left l -> (l::ls,rs)
|
|
|
|
Right r -> (ls,r::rs)
|