From a80ca0b203dc3398a0117d2e1fc6ae5d77250783 Mon Sep 17 00:00:00 2001 From: Siraaj Khandkar Date: Tue, 24 Mar 2015 07:18:40 -0400 Subject: [PATCH] Implement hope_result:(map_error and tag_error) --- src/hope_result.erl | 18 +++++++++++++++++- test/hope_result_SUITE.erl | 20 +++++++++++++++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/hope_result.erl b/src/hope_result.erl index 7cae0a3..dec6e79 100644 --- a/src/hope_result.erl +++ b/src/hope_result.erl @@ -9,6 +9,8 @@ -export( [ return/1 , map/2 + , map_error/2 + , tag_error/2 , pipe/2 , lift_exn/1 , lift_exn/2 @@ -33,6 +35,20 @@ map({ok, X}, F) -> map({error, _}=Error, _) -> Error. +-spec map_error(t(A, B), fun((B) -> (C))) -> + t(A, C). +map_error({ok, _}=Ok, _) -> + Ok; +map_error({error, Reason}, F) -> + {error, F(Reason)}. + +-spec tag_error(t(A, Reason), Tag) -> + t(A, {Tag, Reason}). +tag_error({ok, _}=Ok, _) -> + Ok; +tag_error({error, Reason}, Tag) -> + {error, {Tag, Reason}}. + -spec pipe([F], X) -> t(Ok, Error) when X :: any() @@ -76,6 +92,6 @@ lift_exn(F, Label) when is_function(F, 1) -> try {ok, F(X)} catch Class:Reason -> - {error, {Label, {Class, Reason}}} + tag_error({error, {Class, Reason}}, Label) end end. diff --git a/test/hope_result_SUITE.erl b/test/hope_result_SUITE.erl index 9e60e85..d323cee 100644 --- a/test/hope_result_SUITE.erl +++ b/test/hope_result_SUITE.erl @@ -1,8 +1,5 @@ -module(hope_result_SUITE). -%% TODO: Import only what is used. --include_lib("proper/include/proper.hrl"). - %% Callbacks -export( [ all/0 @@ -19,6 +16,8 @@ , t_lift_exn/1 , t_return/1 , t_map/1 + , t_map_error/1 + , t_tag_error/1 ]). @@ -53,6 +52,8 @@ groups() -> OtherTests = [ t_return , t_map + , t_map_error + , t_tag_error ], Properties = [parallel], [ {?GROUP_PIPE, Properties, PipeTests} @@ -110,3 +111,16 @@ t_map(_Cfg) -> F = fun (foo) -> Y end, {ok, Y} = hope_result:map({ok, X}, F), {error, X} = hope_result:map({error, X}, F). + +t_map_error(_Cfg) -> + X = foo, + Y = bar, + XtoY = fun (foo) -> Y end, + {ok , X} = hope_result:map_error({ok , X}, XtoY), + {error, Y} = hope_result:map_error({error, X}, XtoY). + +t_tag_error(_Cfg) -> + X = foo, + Tag = bar, + {ok , X } = hope_result:tag_error({ok , X}, Tag), + {error, {Tag, X}} = hope_result:tag_error({error, X}, Tag). -- 2.20.1