1use <prelude.kav>
2use <maybe.kav> as maybe
3
4/%
5A linear result type: either `Ok` holding a value of type `a`,
6or `Err` holding an error of type `e`.
7%/
8pub linear datatype Result[a: type, e: type] {
9 | Ok(a)
10 | Err(e)
11}
12
13/%
14Deallocates a result.
15%/
16pub fn free[a: utype, e: utype](r: Result[a, e]) -> one {
17 case r of {
18 | ~Ok(_) => one
19 | ~Err(_) => one
20 }
21}
22
23/%
24Returns a copy of a result.
25%/
26pub fn copy[a: utype, e: utype](r: !Result[a, e]) -> Result[a, e] {
27 case r of {
28 | Ok(x) => Ok(x)
29 | Err(y) => Err(y)
30 }
31}
32
33/%
34Tests whether a result is an `Ok`.
35%/
36pub fn isok[a: type, e: type](r: !Result[a, e]) -> bool {
37 case r of {
38 | Ok(_) => true
39 | Err(_) => false
40 }
41}
42
43/%
44Tests whether a result is an `Err`.
45%/
46pub fn iserr[a: type, e: type](r: !Result[a, e]) -> bool {
47 case r of {
48 | Ok(_) => false
49 | Err(_) => true
50 }
51}
52
53/%
54Returns the value of an `Ok`, or `default` if the result is an `Err`.
55%/
56pub fn okor[a: utype, e: utype](r: Result[a, e], default: a) -> a {
57 case r of {
58 | ~Ok(x) => x
59 | ~Err(_) => default
60 }
61}
62
63/%
64Applies `f` to the value of an `Ok`, leaving an `Err` untouched.
65%/
66pub fn map[a: type, b: type, e: type](r: Result[a, e], f: fn(a) -> b) -> Result[b, e] {
67 case r of {
68 | ~Ok(x) => Ok(f(x))
69 | ~Err(y) => Err(y)
70 }
71}
72
73/%
74Applies `f` to the error of an `Err`, leaving an `Ok` untouched.
75%/
76pub fn maperr[a: type, e: type, d: type](r: Result[a, e], f: fn(e) -> d) -> Result[a, d] {
77 case r of {
78 | ~Ok(x) => Ok(x)
79 | ~Err(y) => Err(f(y))
80 }
81}
82
83/%
84Chains a computation that may fail.
85
86If the result is `Ok(x)`, returns `f(x)`; if it is an `Err`, returns it unchanged.
87%/
88pub fn bind[a: type, b: type, e: type](r: Result[a, e], f: fn(a) -> Result[b, e]) -> Result[b, e] {
89 case r of {
90 | ~Ok(x) => f(x)
91 | ~Err(y) => Err(y)
92 }
93}
94
95/%
96Flattens a nested result.
97%/
98pub fn join[a: type, e: type](r: Result[Result[a, e], e]) -> Result[a, e] {
99 case r of {
100 | ~Ok(inner) => inner
101 | ~Err(y) => Err(y)
102 }
103}
104
105/%
106Collapses a result into a single value.
107
108Applies `f` if the result is an `Ok` and `g` if it is an `Err`.
109%/
110pub fn fold[a: type, e: type, c: type](r: Result[a, e], f: fn(a) -> c, g: fn(e) -> c) -> c {
111 case r of {
112 | ~Ok(x) => f(x)
113 | ~Err(y) => g(y)
114 }
115}
116
117/%
118Tests whether two results are equal.
119%/
120pub fn equal[a: utype, e: utype](r1: !Result[a, e], r2: !Result[a, e], eqok: fn(a, a) -> bool, eqerr: fn(e, e) -> bool) -> bool {
121 case (r1, r2) of {
122 | (Ok(x), Ok(y)) => eqok(x, y)
123 | (Err(x), Err(y)) => eqerr(x, y)
124 | (Ok(_), Err(_)) => false
125 | (Err(_), Ok(_)) => false
126 }
127}