X-Git-Url: https://git.xandkar.net/?a=blobdiff_plain;f=src%2Fhope_result.erl;h=1b217f845b4fa4c7cfff2a07cc272c9be3e7f762;hb=8fc25ea1d79ab2c6148b73260490e804bd76ff7c;hp=405f2e04eb9f9589731039d867f921b2a75189e1;hpb=6731749baadb46eda33393abbff36daae302cac8;p=hope.git diff --git a/src/hope_result.erl b/src/hope_result.erl index 405f2e0..1b217f8 100644 --- a/src/hope_result.erl +++ b/src/hope_result.erl @@ -1,18 +1,48 @@ -module(hope_result). --export_type([ t/2 - ]). --export([ pipe/2 - ]). +-export_type( + [ t/2 + ]). +-export( + [ pipe/2 + , lift_exn/1 + ]). --type t(A, B) :: {ok, A} | {error, B}. +-type t(A, B) :: + {ok, A} + | {error, B} + . + +-spec pipe([F], X) -> + t(Ok, Error) + when X :: any() + , Ok :: any() + , Error :: any() + , F :: fun((X) -> t(Ok, Error)) + . pipe([] , X) -> 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.