on master help sign in
Add examples!
139f73aEvan Czaplicki
libraries/Either.elm+26−4
@@ -26,28 +26,50 @@ data Either a b = Left a | Right b
26
26
27{-| Apply the first function to a `Left` and the second function to a `Right`.
27{-| Apply the first function to a `Left` and the second function to a `Right`.
28This allows the extraction of a value from an `Either`.
28This allows the extraction of a value from an `Either`.
29+
30+ either (\n -> n + 1) sqrt (Left 4) == 5
31+ either (\n -> n + 1) sqrt (Right 4) == 2
32+
33+ map : (a -> b) -> Either err a -> Either err b
34+ map f e = either Left (\x -> Right (f x)) e
29-}
35-}
30either : (a -> c) -> (b -> c) -> Either a b -> c
36either : (a -> c) -> (b -> c) -> Either a b -> c
31either f g e = case e of { Left x -> f x ; Right y -> g y }
37either f g e = case e of { Left x -> f x ; Right y -> g y }
32
38
33−{-| True if the value is a `Left`. -}
39+{-| True if the value is a `Left`.
40+
41+ isLeft (Left "Cat") == True
42+ isLeft (Right 1123) == False
43+-}
34isLeft : Either a b -> Bool
44isLeft : Either a b -> Bool
35isLeft e = case e of { Left _ -> True ; _ -> False }
45isLeft e = case e of { Left _ -> True ; _ -> False }
36
46
37−{-| True if the value is a `Right`. -}
47+{-| True if the value is a `Right`.
48+
49+ isRight (Left "Cat") == False
50+ isRight (Right 1123) == True
51+-}
38isRight : Either a b -> Bool
52isRight : Either a b -> Bool
39isRight e = case e of { Right _ -> True ; _ -> False }
53isRight e = case e of { Right _ -> True ; _ -> False }
40
54
41−{-| Keep only the values held in `Left` values. -}
55+{-| Keep only the values held in `Left` values.
56+
57+ lefts [Left 3, Right 'a', Left 5, Right "eight"] == [3,5]
58+-}
42lefts : [Either a b] -> [a]
59lefts : [Either a b] -> [a]
43lefts es = List.foldr consLeft [] es
60lefts es = List.foldr consLeft [] es
44
61
45−{-| Keep only the values held in `Right` values. -}
62+{-| Keep only the values held in `Right` values.
63+
64+ rights [Left 3, Right 'a', Left 5, Right 'b'] == ['a','b']
65+-}
46rights : [Either a b] -> [b]
66rights : [Either a b] -> [b]
47rights es = List.foldr consRight [] es
67rights es = List.foldr consRight [] es
48
68
49{-| Split into two lists, lefts on the left and rights on the right. So we
69{-| Split into two lists, lefts on the left and rights on the right. So we
50have the equivalence: `(partition es == (lefts es, rights es))`
70have the equivalence: `(partition es == (lefts es, rights es))`
71+
72+ partition [Left 3, Right 'a', Left 5, Right 'b'] == ([3,5],['a','b'])
51-}
73-}
52partition : [Either a b] -> ([a],[b])
74partition : [Either a b] -> ([a],[b])
53partition es = List.foldr consEither ([],[]) es
75partition es = List.foldr consEither ([],[]) es