Commit | Line | Data |
---|---|---|
e492ea13 SK |
1 | -module(hope_option). |
2 | ||
4af0774b | 3 | -behavior(hope_monad). |
2a40de4f | 4 | |
3b156801 SK |
5 | -export_type( |
6 | [ t/1 | |
7 | ]). | |
e492ea13 | 8 | |
3b156801 SK |
9 | -export( |
10 | [ put/2 | |
11 | , get/2 | |
4af0774b | 12 | , return/1 |
3b156801 | 13 | , map/2 |
27a4f25f | 14 | , iter/2 |
4af0774b | 15 | , pipe/2 |
2497062c | 16 | , of_result/1 |
3b156801 | 17 | ]). |
e492ea13 SK |
18 | |
19 | ||
3b156801 SK |
20 | -type t(A) :: |
21 | none | |
22 | | {some, A} | |
23 | . | |
e492ea13 SK |
24 | |
25 | ||
ed9905af SK |
26 | -spec put(A, fun((A) -> boolean())) -> |
27 | t(A). | |
e492ea13 SK |
28 | put(X, F) -> |
29 | case F(X) | |
30 | of true -> {some, X} | |
31 | ; false -> none | |
32 | end. | |
33 | ||
ed9905af SK |
34 | -spec get(t(A), Default :: A) -> |
35 | A. | |
e492ea13 SK |
36 | get({some, X}, _) -> X; |
37 | get(none , Y) -> Y. | |
38 | ||
4af0774b SK |
39 | -spec return(A) -> |
40 | {some, A}. | |
41 | return(X) -> | |
42 | {some, X}. | |
43 | ||
ed9905af SK |
44 | -spec map(t(A), fun((A) -> (B))) -> |
45 | t(B). | |
e492ea13 SK |
46 | map({some, X}, F) -> {some, F(X)}; |
47 | map(none , _) -> none. | |
27a4f25f SK |
48 | |
49 | -spec iter(t(A), fun((A) -> (ok))) -> | |
50 | ok. | |
51 | iter({some, X}, F) -> ok = F(X); | |
52 | iter(none , _) -> ok. | |
2497062c | 53 | |
4af0774b SK |
54 | -spec pipe([fun((A) -> t(B))], A) -> |
55 | t(B). | |
56 | pipe([], X) -> | |
57 | return(X); | |
58 | pipe([F|Fs], X) -> | |
59 | case F(X) | |
60 | of none -> none | |
61 | ; {some, Y} -> pipe(Fs, Y) | |
62 | end. | |
63 | ||
2497062c SK |
64 | -spec of_result(hope_result:t(A, _B)) -> |
65 | t(A). | |
66 | of_result({ok, X}) -> {some, X}; | |
67 | of_result({error, _}) -> none. |