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