std:Optional
lib/Optional.omg
lib/Optional.omg46 lines
1{- Optional values.
2
3 `Optional a` is a builtin type with the constructors `Some x` and
4 `None a`; its eliminator is the builtin `Optional/elim`.
5-}
6
7-- fold f z (Some x) = f x; fold f z (None a) = z
8let fold
9 : forall {la lb : Level} {a : Type la} {b : Type lb} -> (a -> b) -> b -> Optional a -> b
10 = \{la} {lb} {a} {b} some none -> Optional/elim (\(_ : Optional a) -> b) none some
11
12let map
13 : forall {la lb : Level} {a : Type la} {b : Type lb} -> (a -> b) -> Optional a -> Optional b
14 = \{la} {lb} {a} {b} f -> fold (\(x : a) -> Some (f x)) (None b)
15
16-- The value, or a default if there is none.
17let default
18 : forall {l : Level} {a : Type l} -> a -> Optional a -> a
19 = \{l} {a} fallback -> fold (\(x : a) -> x) fallback
20
21let isSome
22 : forall {l : Level} {a : Type l} -> Optional a -> Bool
23 = \{l} {a} -> fold (\(_ : a) -> True) False
24
25let isNone
26 : forall {l : Level} {a : Type l} -> Optional a -> Bool
27 = \{l} {a} -> fold (\(_ : a) -> False) True
28
29let toList
30 : forall {l : Level} {a : Type l} -> Optional a -> List a
31 = \{l} {a} -> fold (\(x : a) -> [ x ]) ([] : List a)
32
33-- Chain a computation that may fail after another one.
34let andThen
35 : forall {la lb : Level} {a : Type la} {b : Type lb}
36 -> Optional a
37 -> (a -> Optional b)
38 -> Optional b
39 = \{la} {lb} {a} {b} o f -> fold f (None b) o
40
41-- The first value, or else the second.
42let orElse
43 : forall {l : Level} {a : Type l} -> Optional a -> Optional a -> Optional a
44 = \{l} {a} first second -> fold (\(x : a) -> Some x) second first
45
46in { fold, map, default, isSome, isNone, toList, andThen, orElse }