Re-order exports to clearly show monad interface.
[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 % 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).
33put(X, F) ->
34 return(X, F).
35
36-spec get(t(A), Default :: A) ->
37 A.
38get({some, X}, _) -> X;
39get(none , Y) -> Y.
40
41-spec return(A) ->
42 {some, A}.
43return(X) ->
44 {some, X}.
45
46-spec return(A, fun((A) -> boolean())) ->
47 t(A).
48return(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).
56map({some, X}, F) -> {some, F(X)};
57map(none , _) -> none.
58
59-spec iter(t(A), fun((A) -> (ok))) ->
60 ok.
61iter({some, X}, F) -> ok = F(X);
62iter(none , _) -> ok.
63
64-spec pipe([fun((A) -> t(B))], A) ->
65 t(B).
66pipe([], X) ->
67 return(X);
68pipe([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).
76of_result({ok, X}) -> {some, X};
77of_result({error, _}) -> none.
78
79-spec of_undefined(undefined | A) ->
80 t(A).
81of_undefined(undefined) -> none;
82of_undefined(X) -> {some, X}.
This page took 0.019794 seconds and 4 git commands to generate.