| 1 | -module(hope_option). |
| 2 | |
| 3 | -behavior(hope_gen_monad). |
| 4 | |
| 5 | -export_type( |
| 6 | [ t/1 |
| 7 | ]). |
| 8 | |
| 9 | -export( |
| 10 | % Generic monad interface |
| 11 | [ return/1 |
| 12 | , map/2 |
| 13 | , pipe/2 |
| 14 | |
| 15 | % Specific to hope_option:t() |
| 16 | , return/2 |
| 17 | , put/2 |
| 18 | , get/2 |
| 19 | , iter/2 |
| 20 | , of_result/1 |
| 21 | , of_undefined/1 |
| 22 | ]). |
| 23 | |
| 24 | |
| 25 | -type t(A) :: |
| 26 | none |
| 27 | | {some, A} |
| 28 | . |
| 29 | |
| 30 | |
| 31 | -spec put(A, fun((A) -> boolean())) -> |
| 32 | t(A). |
| 33 | put(X, F) -> |
| 34 | return(X, F). |
| 35 | |
| 36 | -spec get(t(A), Default :: A) -> |
| 37 | A. |
| 38 | get({some, X}, _) -> X; |
| 39 | get(none , Y) -> Y. |
| 40 | |
| 41 | -spec return(A) -> |
| 42 | {some, A}. |
| 43 | return(X) -> |
| 44 | {some, X}. |
| 45 | |
| 46 | -spec return(A, fun((A) -> boolean())) -> |
| 47 | t(A). |
| 48 | return(X, Condition) -> |
| 49 | case Condition(X) |
| 50 | of true -> {some, X} |
| 51 | ; false -> none |
| 52 | end. |
| 53 | |
| 54 | -spec map(t(A), fun((A) -> (B))) -> |
| 55 | t(B). |
| 56 | map({some, X}, F) -> {some, F(X)}; |
| 57 | map(none , _) -> none. |
| 58 | |
| 59 | -spec iter(t(A), fun((A) -> (ok))) -> |
| 60 | ok. |
| 61 | iter({some, X}, F) -> ok = F(X); |
| 62 | iter(none , _) -> ok. |
| 63 | |
| 64 | -spec pipe([fun((A) -> t(B))], A) -> |
| 65 | t(B). |
| 66 | pipe([], X) -> |
| 67 | return(X); |
| 68 | pipe([F|Fs], X) -> |
| 69 | case F(X) |
| 70 | of none -> none |
| 71 | ; {some, Y} -> pipe(Fs, Y) |
| 72 | end. |
| 73 | |
| 74 | -spec of_result(hope_result:t(A, _B)) -> |
| 75 | t(A). |
| 76 | of_result({ok, X}) -> {some, X}; |
| 77 | of_result({error, _}) -> none. |
| 78 | |
| 79 | -spec of_undefined(undefined | A) -> |
| 80 | t(A). |
| 81 | of_undefined(undefined) -> none; |
| 82 | of_undefined(X) -> {some, X}. |