bitwise shrub/kav / lib / maybe.kav
 1use <prelude.kav>
 2use <fun.kav> as fun
 3
 4/%
 5An optional value: either `None`, or `Some(x)` holding a value of type `a`.
 6%/
 7pub linear datatype Maybe[a:type] {
 8    | None
 9    | Some(a)
10}
11
12pub fn free[a: utype](maybe: Maybe[a]) -> one {
13    case maybe of {
14    | ~Some(_) => one
15    | ~None => one
16    }
17}
18
19/%
20Tests whether two optional integers are equal.
21%/
22pub fn equal(maybe1: !Maybe[int], maybe2: !Maybe[int]) -> bool {
23    case (maybe1, maybe2) of {
24        | (None, None) => true
25        | (Some(x), Some(y)) => x == y
26        | (None, Some(_)) => false
27        | (Some(_), None) => false
28    }
29}
30
31/%
32Wraps `x` in `Some` if `cond` is `true`, and returns `None` otherwise.
33%/
34pub fn some_if[a: utype](cond: bool, x: a) -> Maybe[a] {
35    if cond then Some(x) else None
36}
37
38/%
39Applies `f` to the value inside a `Maybe`, if there is one.
40%/
41pub fn map[a: type, b: type](maybe: Maybe[a], f: fn(a) -> b) -> Maybe[b] {
42    case maybe of {
43        | ~None => None
44        | ~Some(x) => Some(f(x))
45    }
46}
47
48/%
49Wraps a value in `Some`.
50%/
51pub fn pure[a: type](x: a) -> Maybe[a] {
52    Some(x)
53}
54
55/%
56Combines the values of two `Maybe`s using `f`.
57
58Returns `Some(f(x, y))` if both hold a value, and `None` if either is empty.
59%/
60pub fn map2[a: utype, b: utype, c: type](m1: Maybe[a], m2: Maybe[b], f: fn(a, b) -> c) -> Maybe[c] {
61    case (m1, m2) of {
62        | (~Some(x), ~Some(y)) => Some(f(x, y))
63        | (x, y) => {
64            val _ = free(x)
65            val _ = free(y)
66            None
67        }
68    }
69}
70
71/%
72Chains a computation that may itself fail.
73%/
74pub fn bind[a: type, b: type](maybe: Maybe[a], f: fn(a) -> Maybe[b]) -> Maybe[b] {
75    case maybe of {
76        | ~None => None
77        | ~Some(x) => f(x)
78    }
79}
80
81/%
82Eliminates a `Maybe` into a plain value.
83
84If it holds `x`, returns `f(x)`; if it is empty, returns
85`default`.
86%/
87pub fn fold[a: type, b: utype](default: b, maybe: Maybe[a], f: fn(a) -> b) -> b {
88    case maybe of {
89        | ~None => default
90        | ~Some(x) => f(x)
91    }
92}
93
94/%
95Returns the value inside a `Maybe`, or `default` if it is empty.
96%/
97pub fn value[a: utype](default: a, maybe: Maybe[a]) -> a {
98    fold(default, maybe, fun::id)
99}