From 54ab0c82897759fb29293b9b872f444dc1408dab Mon Sep 17 00:00:00 2001 From: Siraaj Khandkar Date: Thu, 30 Jul 2015 00:35:31 -0400 Subject: [PATCH] Add hope_list:map_result/2 --- src/hope.app.src | 2 +- src/hope_list.erl | 18 +++++++++++++++++- test/hope_list_SUITE.erl | 12 ++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/hope.app.src b/src/hope.app.src index d2b376c..c5c860f 100644 --- a/src/hope.app.src +++ b/src/hope.app.src @@ -1,7 +1,7 @@ {application, hope, [ {description, "Higher Order Programming in Erlang"}, - {vsn, "3.6.0"}, + {vsn, "3.7.0"}, {registered, []}, {applications, [ kernel, diff --git a/src/hope_list.erl b/src/hope_list.erl index f179d1a..63d9c99 100644 --- a/src/hope_list.erl +++ b/src/hope_list.erl @@ -10,6 +10,7 @@ , map/3 % Tunable recursion limit , map_rev/2 , map_slow/2 + , map_result/2 % Not tail-recursive , first_match/2 ]). @@ -66,7 +67,6 @@ map([X1, X2, X3, X4, X5 | Xs], F, RecursionLimit, RecursionCount) -> end, [Y1, Y2, Y3, Y4, Y5 | Ys]. - %% @doc lists:reverse(map_rev(L, F)) %% @end -spec map_slow([A], fun((A) -> (B))) -> @@ -91,6 +91,22 @@ map_rev_acc([X|Xs], F, Ys) -> Y = F(X), map_rev_acc(Xs, F, [Y|Ys]). +-spec map_result([A], fun((A) -> (hope_result:t(B, C)))) -> + hope_result:t([B], C). +map_result([], _) -> + {ok, []}; +map_result([X | Xs], F) -> + case F(X) + of {ok, Y} -> + case map_result(Xs, F) + of {ok, Ys} -> + {ok, [Y | Ys]} + ; {error, _}=Error -> + Error + end + ; {error, _}=Error -> + Error + end. -spec unique_preserve_order(t(A)) -> t(A). diff --git a/test/hope_list_SUITE.erl b/test/hope_list_SUITE.erl index 9557aab..7152503 100644 --- a/test/hope_list_SUITE.erl +++ b/test/hope_list_SUITE.erl @@ -16,6 +16,7 @@ , t_map_slow/1 , t_map/1 , t_map_3/1 + , t_map_result/1 ]). @@ -39,6 +40,7 @@ groups() -> , t_map_slow , t_map , t_map_3 + , t_map_result ], Properties = [parallel], [{?GROUP, Properties, Tests}]. @@ -89,3 +91,13 @@ prop_unique_preserve_order() -> t_hope_list_specs(_) -> [] = proper:check_specs(hope_list). + +t_map_result(_Cfg) -> + AssertPositive = + fun (I) when I > 0 -> {ok, I}; (_) -> {error, negative} end, + AllPositives = lists:seq(1, 5), + AllNegatives = lists:seq(-5, -1), + Mixed = lists:seq(-5, 5), + {ok, AllPositives} = hope_list:map_result(AllPositives, AssertPositive), + {error, negative} = hope_list:map_result(AllNegatives, AssertPositive), + {error, negative} = hope_list:map_result(Mixed, AssertPositive). -- 2.20.1