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