Implement hope_list:map_rev/2
[hope.git] / src / hope_list.erl
CommitLineData
a6244ba2
SK
1-module(hope_list).
2
3-export_type(
4 [ t/1
5 ]).
6
7-export(
8 [ unique_preserve_order/1
c66ddf80 9 , map_rev/2
a6244ba2
SK
10 ]).
11
12
13-type t(A) ::
14 [A].
15
16
c66ddf80
SK
17%% @doc O(N), tail-recursive equivalent to lists:rev(lists:map(F, L))
18%% @end
19-spec map_rev([A], fun((A) -> (B))) ->
20 [B].
21map_rev(Xs, F) ->
22 map_rev_acc(Xs, F, []).
23
24-spec map_rev_acc([A], fun((A) -> (B)), [B]) ->
25 [B].
26map_rev_acc([], _, Ys) ->
27 Ys;
28map_rev_acc([X|Xs], F, Ys) ->
29 Y = F(X),
30 map_rev_acc(Xs, F, [Y|Ys]).
31
32
a6244ba2
SK
33-spec unique_preserve_order(t(A)) ->
34 t(A).
35unique_preserve_order(L) ->
17b5d686 36 PrependIfNew =
a6244ba2
SK
37 fun (X, Xs) ->
38 case lists:member(X, Xs)
17b5d686
SK
39 of true -> Xs
40 ; false -> [X | Xs]
a6244ba2
SK
41 end
42 end,
17b5d686 43 lists:reverse(lists:foldl(PrependIfNew, [], L)).
This page took 0.034256 seconds and 4 git commands to generate.