X-Git-Url: https://git.xandkar.net/?a=blobdiff_plain;f=src%2Fhope_result.erl;h=7cae0a355b463c7ed143475afad234d8a893048b;hb=b69220d7a75faba9743d5b89b6fa40443cd39eec;hp=5d0ea7e42c40521a8a24f65b0fa0ce7f4701153c;hpb=ed9905af6fa1dba6f89759d6dbfc970426122bde;p=hope.git diff --git a/src/hope_result.erl b/src/hope_result.erl index 5d0ea7e..7cae0a3 100644 --- a/src/hope_result.erl +++ b/src/hope_result.erl @@ -1,12 +1,17 @@ -module(hope_result). +-behavior(hope_gen_monad). -export_type( [ t/2 ]). -export( - [ pipe/2 + [ return/1 + , map/2 + , pipe/2 + , lift_exn/1 + , lift_exn/2 ]). @@ -16,6 +21,18 @@ . +-spec return(A) -> + {ok, A}. +return(X) -> + {ok, X}. + +-spec map(t(A, Error), fun((A) -> (B))) -> + t(B, Error). +map({ok, X}, F) -> + {ok, F(X)}; +map({error, _}=Error, _) -> + Error. + -spec pipe([F], X) -> t(Ok, Error) when X :: any() @@ -23,9 +40,42 @@ , Error :: any() , F :: fun((X) -> t(Ok, Error)) . -pipe([] , X) -> X; +pipe([], X) -> + {ok, X}; pipe([F|Fs], X) -> case F(X) of {error, _}=E -> E ; {ok, Y} -> pipe(Fs, Y) end. + +-spec lift_exn(F) -> G + when F :: fun((A)-> B) + , G :: fun((A)-> t(B, {Class, Reason :: any()})) + , Class :: error + | exit + | throw + . +lift_exn(F) when is_function(F, 1) -> + fun(X) -> + try + {ok, F(X)} + catch Class:Reason -> + {error, {Class, Reason}} + end + end. + +-spec lift_exn(F, Label) -> G + when F :: fun((A)-> B) + , G :: fun((A)-> t(B, {Label, {Class, Reason :: any()}})) + , Class :: error + | exit + | throw + . +lift_exn(F, Label) when is_function(F, 1) -> + fun(X) -> + try + {ok, F(X)} + catch Class:Reason -> + {error, {Label, {Class, Reason}}} + end + end.