on 727d708 help sign in
elk/libraries/Either.elm
52 lines 1.5 kB history raw
2module Either where
4import List
6-- Represents any data that can take two different types.
7--
8-- This can also be used for error handling `(Either String a)` where error
9-- messages are stored on the left, and the correct values (“right”
10-- values) are stored on the right.
11data Either a b = Left a | Right b
13-- Apply the first function to a `Left` and the second function to a `Right`.
14-- This allows the extraction of a value from an `Either`.
15either : (a -> c) -> (b -> c) -> Either a b -> c
16either f g e = case e of { Left x -> f x ; Right y -> g y }
18-- True if the value is a `Left`.
19isLeft : Either a b -> Bool
20isLeft e = case e of { Left _ -> True ; _ -> False }
22-- True if the value is a `Right`.
23isRight : Either a b -> Bool
24isRight e = case e of { Right _ -> True ; _ -> False }
26-- Keep only the values held in `Left` values.
27lefts : [Either a b] -> [a]
28lefts es = List.foldr consLeft [] es
30-- Keep only the values held in `Right` values.
31rights : [Either a b] -> [b]
32rights es = List.foldr consRight [] es
34-- Split into two lists, lefts on the left and rights on the right. So we
35-- have the equivalence: `(partition es == (lefts es, rights es))`
36partition : [Either a b] -> ([a],[b])
37partition es = List.foldr consEither ([],[]) es
39consLeft e vs =
40 case e of
41 Left v -> v::vs
42 Right _ -> vs
44consRight e vs =
45 case e of
46 Left _ -> vs
47 Right v -> v::vs
49consEither e (ls,rs) =
50 case e of
51 Left l -> (l::ls,rs)
52 Right r -> (ls,r::rs)