X-Git-Url: https://git.xandkar.net/?a=blobdiff_plain;f=src%2Fhope_list.erl;h=f179d1a054a2dabb46351eef14bf81e64aa9bc8f;hb=64617423d513e37494369d637bee5ff357de791b;hp=b93ad2d346d08d42f5dd277907de7255114ea1cb;hpb=c66ddf8079f01284853e24ca129062c3d11229b0;p=hope.git diff --git a/src/hope_list.erl b/src/hope_list.erl index b93ad2d..f179d1a 100644 --- a/src/hope_list.erl +++ b/src/hope_list.erl @@ -6,15 +6,77 @@ -export( [ unique_preserve_order/1 + , map/2 + , map/3 % Tunable recursion limit , map_rev/2 + , map_slow/2 + , first_match/2 ]). +-define(DEFAULT_RECURSION_LIMIT, 1000). + + -type t(A) :: [A]. -%% @doc O(N), tail-recursive equivalent to lists:rev(lists:map(F, L)) +%% @doc Tail-recursive equivalent of lists:map/2 +%% @end +-spec map([A], fun((A) -> (B))) -> + [B]. +map(Xs, F) -> + map(Xs, F, ?DEFAULT_RECURSION_LIMIT). + +-spec map([A], fun((A) -> (B)), RecursionLimit :: non_neg_integer()) -> + [B]. +map(Xs, F, RecursionLimit) -> + map(Xs, F, RecursionLimit, 0). + +map([], _, _, _) -> + []; +map([X1], F, _, _) -> + Y1 = F(X1), + [Y1]; +map([X1, X2], F, _, _) -> + Y1 = F(X1), + Y2 = F(X2), + [Y1, Y2]; +map([X1, X2, X3], F, _, _) -> + Y1 = F(X1), + Y2 = F(X2), + Y3 = F(X3), + [Y1, Y2, Y3]; +map([X1, X2, X3, X4], F, _, _) -> + Y1 = F(X1), + Y2 = F(X2), + Y3 = F(X3), + Y4 = F(X4), + [Y1, Y2, Y3, Y4]; +map([X1, X2, X3, X4, X5 | Xs], F, RecursionLimit, RecursionCount) -> + Y1 = F(X1), + Y2 = F(X2), + Y3 = F(X3), + Y4 = F(X4), + Y5 = F(X5), + Ys = + case RecursionCount > RecursionLimit + of true -> map_slow(Xs, F) + ; false -> map (Xs, F, RecursionLimit, RecursionCount + 1) + end, + [Y1, Y2, Y3, Y4, Y5 | Ys]. + + +%% @doc lists:reverse(map_rev(L, F)) +%% @end +-spec map_slow([A], fun((A) -> (B))) -> + [B]. +map_slow(Xs, F) -> + lists:reverse(map_rev(Xs, F)). + + +%% @doc Tail-recursive alternative to lists:map/2, which accumulates and +%% returns list in reverse order. %% @end -spec map_rev([A], fun((A) -> (B))) -> [B]. @@ -41,3 +103,13 @@ unique_preserve_order(L) -> end end, lists:reverse(lists:foldl(PrependIfNew, [], L)). + +-spec first_match([{Tag, fun((A) -> boolean())}], A) -> + hope_option:t(Tag). +first_match([], _) -> + none; +first_match([{Tag, F} | Tests], X) -> + case F(X) + of true -> {some, Tag} + ; false -> first_match(Tests, X) + end.