Commit | Line | Data |
---|---|---|
6731749b SK |
1 | -module(hope_result). |
2 | ||
2a40de4f | 3 | |
3b156801 SK |
4 | -export_type( |
5 | [ t/2 | |
6 | ]). | |
6731749b | 7 | |
3b156801 SK |
8 | -export( |
9 | [ pipe/2 | |
8fc25ea1 | 10 | , lift_exn/1 |
3b156801 | 11 | ]). |
6731749b SK |
12 | |
13 | ||
3b156801 SK |
14 | -type t(A, B) :: |
15 | {ok, A} | |
16 | | {error, B} | |
17 | . | |
6731749b SK |
18 | |
19 | ||
ed9905af SK |
20 | -spec pipe([F], X) -> |
21 | t(Ok, Error) | |
22 | when X :: any() | |
23 | , Ok :: any() | |
24 | , Error :: any() | |
25 | , F :: fun((X) -> t(Ok, Error)) | |
26 | . | |
3efbdbc9 SK |
27 | pipe([], X) -> |
28 | {ok, X}; | |
6731749b SK |
29 | pipe([F|Fs], X) -> |
30 | case F(X) | |
31 | of {error, _}=E -> E | |
32 | ; {ok, Y} -> pipe(Fs, Y) | |
33 | end. | |
8fc25ea1 SK |
34 | |
35 | -spec lift_exn(F) -> G | |
36 | when F :: fun((A)-> B) | |
37 | , G :: fun((A)-> t(B, {Class, Reason :: any()})) | |
38 | , Class :: error | |
39 | | exit | |
40 | | throw | |
41 | . | |
42 | lift_exn(F) when is_function(F, 1) -> | |
43 | fun(X) -> | |
44 | try | |
45 | {ok, F(X)} | |
46 | catch Class:Reason -> | |
47 | {error, {Class, Reason}} | |
48 | end | |
49 | end. |