180c41687cd7ea5582c8c6901b5fba7dbba8e72e
[hope.git] / src / hope_option.erl
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 ]).
18
19
20 -type t(A) ::
21 none
22 | {some, A}
23 .
24
25
26 -spec put(A, fun((A) -> boolean())) ->
27 t(A).
28 put(X, F) ->
29 case F(X)
30 of true -> {some, X}
31 ; false -> none
32 end.
33
34 -spec get(t(A), Default :: A) ->
35 A.
36 get({some, X}, _) -> X;
37 get(none , Y) -> Y.
38
39 -spec return(A) ->
40 {some, A}.
41 return(X) ->
42 {some, X}.
43
44 -spec map(t(A), fun((A) -> (B))) ->
45 t(B).
46 map({some, X}, F) -> {some, F(X)};
47 map(none , _) -> none.
48
49 -spec iter(t(A), fun((A) -> (ok))) ->
50 ok.
51 iter({some, X}, F) -> ok = F(X);
52 iter(none , _) -> ok.
53
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
64 -spec of_result(hope_result:t(A, _B)) ->
65 t(A).
66 of_result({ok, X}) -> {some, X};
67 of_result({error, _}) -> none.
This page took 0.041625 seconds and 3 git commands to generate.