feda5379c1e6ec36e506530547937928b79e82a9
[hope.git] / src / hope_result.erl
1 -module(hope_result).
2
3
4 -export_type(
5 [ t/2
6 ]).
7
8 -export(
9 [ pipe/2
10 , lift_exn/1
11 , lift_exn/2
12 ]).
13
14
15 -type t(A, B) ::
16 {ok, A}
17 | {error, B}
18 .
19
20
21 -spec pipe([F], X) ->
22 t(Ok, Error)
23 when X :: any()
24 , Ok :: any()
25 , Error :: any()
26 , F :: fun((X) -> t(Ok, Error))
27 .
28 pipe([], X) ->
29 {ok, X};
30 pipe([F|Fs], X) ->
31 case F(X)
32 of {error, _}=E -> E
33 ; {ok, Y} -> pipe(Fs, Y)
34 end.
35
36 -spec lift_exn(F) -> G
37 when F :: fun((A)-> B)
38 , G :: fun((A)-> t(B, {Class, Reason :: any()}))
39 , Class :: error
40 | exit
41 | throw
42 .
43 lift_exn(F) when is_function(F, 1) ->
44 fun(X) ->
45 try
46 {ok, F(X)}
47 catch Class:Reason ->
48 {error, {Class, Reason}}
49 end
50 end.
51
52 -spec lift_exn(F, Label) -> G
53 when F :: fun((A)-> B)
54 , G :: fun((A)-> t(B, {Label, {Class, Reason :: any()}}))
55 , Class :: error
56 | exit
57 | throw
58 .
59 lift_exn(F, Label) when is_function(F, 1) ->
60 fun(X) ->
61 try
62 {ok, F(X)}
63 catch Class:Reason ->
64 {error, {Label, {Class, Reason}}}
65 end
66 end.
This page took 0.044411 seconds and 3 git commands to generate.