From c66ddf8079f01284853e24ca129062c3d11229b0 Mon Sep 17 00:00:00 2001 From: Siraaj Khandkar Date: Sun, 21 Dec 2014 03:10:06 -0500 Subject: [PATCH] Implement hope_list:map_rev/2 O(N), tail-recursive equivalent to lists:rev(lists:map(F, L)) --- src/hope.app.src | 2 +- src/hope_list.erl | 17 +++++++++++++++++ test/hope_list_SUITE.erl | 7 +++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/hope.app.src b/src/hope.app.src index 6ea0b7c..eb6f442 100644 --- a/src/hope.app.src +++ b/src/hope.app.src @@ -1,7 +1,7 @@ {application, hope, [ {description, "Higher Order Programming in Erlang"}, - {vsn, "1.4.0"}, + {vsn, "1.5.0"}, {registered, []}, {applications, [ kernel, diff --git a/src/hope_list.erl b/src/hope_list.erl index 9ce451e..b93ad2d 100644 --- a/src/hope_list.erl +++ b/src/hope_list.erl @@ -6,6 +6,7 @@ -export( [ unique_preserve_order/1 + , map_rev/2 ]). @@ -13,6 +14,22 @@ [A]. +%% @doc O(N), tail-recursive equivalent to lists:rev(lists:map(F, L)) +%% @end +-spec map_rev([A], fun((A) -> (B))) -> + [B]. +map_rev(Xs, F) -> + map_rev_acc(Xs, F, []). + +-spec map_rev_acc([A], fun((A) -> (B)), [B]) -> + [B]. +map_rev_acc([], _, Ys) -> + Ys; +map_rev_acc([X|Xs], F, Ys) -> + Y = F(X), + map_rev_acc(Xs, F, [Y|Ys]). + + -spec unique_preserve_order(t(A)) -> t(A). unique_preserve_order(L) -> diff --git a/test/hope_list_SUITE.erl b/test/hope_list_SUITE.erl index fd2393c..f591e83 100644 --- a/test/hope_list_SUITE.erl +++ b/test/hope_list_SUITE.erl @@ -12,6 +12,7 @@ -export( [ t_unique_preserve_order/1 , t_hope_list_specs/1 + , t_map_rev/1 ]). @@ -31,6 +32,7 @@ groups() -> Tests = [ t_unique_preserve_order , t_hope_list_specs + , t_map_rev ], Properties = [parallel], [{?GROUP, Properties, Tests}]. @@ -40,6 +42,11 @@ groups() -> %% Test cases %% ============================================================================= +t_map_rev(_Cfg) -> + F = fun (N) -> N + 1 end, + [4, 3, 2] = hope_list:map_rev([1, 2, 3], F), + [] = hope_list:map_rev([], F). + t_unique_preserve_order(_Cfg) -> ?PROPTEST(prop_unique_preserve_order). -- 2.20.1