on 4bec310 help sign in
elk/libraries/Either.elm
90 lines 2.3 kB history raw
1module Either where
3{-| Represents any data that can take two different types.
5# Type and Constructors
6@docs Either
8# Taking Eithers apart
9@docs either, isLeft, isRight
11# Eithers and Lists
12@docs lefts, rights, partition
14-}
16import List
18{-| Represents any data may take two forms. For example, a user ID may be
19either an `Int` or a `String`.
21This can also be used for error handling `(Either String a)` where
22error messages are stored on the left, and the correct values
23(“right” values) are stored on the right.
24-}
25data Either a b = Left a | Right b
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`.
30 either (\n -> n + 1) sqrt (Left 4) == 5
31 either (\n -> n + 1) sqrt (Right 4) == 2
33 map : (a -> b) -> Either err a -> Either err b
34 map f e = either Left (\x -> Right (f x)) e
35-}
36either : (a -> c) -> (b -> c) -> Either a b -> c
37either f g e = case e of { Left x -> f x ; Right y -> g y }
39{-| True if the value is a `Left`.
41 isLeft (Left "Cat") == True
42 isLeft (Right 1123) == False
43-}
44isLeft : Either a b -> Bool
45isLeft e = case e of { Left _ -> True ; _ -> False }
47{-| True if the value is a `Right`.
49 isRight (Left "Cat") == False
50 isRight (Right 1123) == True
51-}
52isRight : Either a b -> Bool
53isRight e = case e of { Right _ -> True ; _ -> False }
55{-| Keep only the values held in `Left` values.
57 lefts [Left 3, Right 'a', Left 5, Right "eight"] == [3,5]
58-}
59lefts : [Either a b] -> [a]
60lefts es = List.foldr consLeft [] es
62{-| Keep only the values held in `Right` values.
64 rights [Left 3, Right 'a', Left 5, Right 'b'] == ['a','b']
65-}
66rights : [Either a b] -> [b]
67rights es = List.foldr consRight [] es
69{-| Split into two lists, lefts on the left and rights on the right. So we
70have the equivalence: `(partition es == (lefts es, rights es))`
72 partition [Left 3, Right 'a', Left 5, Right 'b'] == ([3,5],['a','b'])
73-}
74partition : [Either a b] -> ([a],[b])
75partition es = List.foldr consEither ([],[]) es
77consLeft e vs =
78 case e of
79 Left v -> v::vs
80 Right _ -> vs
82consRight e vs =
83 case e of
84 Left _ -> vs
85 Right v -> v::vs
87consEither e (ls,rs) =
88 case e of
89 Left l -> (l::ls,rs)
90 Right r -> (ls,r::rs)