Add has_key/2 dictionary method.
[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
ff793acf 9 , map/2
781f182f 10 , map/3 % Tunable recursion limit
c66ddf80 11 , map_rev/2
2a81fbac 12 , map_slow/2
a626cf31 13 , first_match/2
a6244ba2
SK
14 ]).
15
16
781f182f 17-define(DEFAULT_RECURSION_LIMIT, 1000).
ff793acf
SK
18
19
a6244ba2
SK
20-type t(A) ::
21 [A].
22
23
ff793acf
SK
24%% @doc Tail-recursive equivalent of lists:map/2
25%% @end
26-spec map([A], fun((A) -> (B))) ->
27 [B].
28map(Xs, F) ->
781f182f 29 map(Xs, F, ?DEFAULT_RECURSION_LIMIT).
ff793acf 30
781f182f 31-spec map([A], fun((A) -> (B)), RecursionLimit :: non_neg_integer()) ->
ff793acf 32 [B].
781f182f
SK
33map(Xs, F, RecursionLimit) ->
34 map(Xs, F, RecursionLimit, 0).
35
36map([], _, _, _) ->
ff793acf 37 [];
781f182f 38map([X1], F, _, _) ->
ff793acf
SK
39 Y1 = F(X1),
40 [Y1];
781f182f 41map([X1, X2], F, _, _) ->
ff793acf
SK
42 Y1 = F(X1),
43 Y2 = F(X2),
44 [Y1, Y2];
781f182f 45map([X1, X2, X3], F, _, _) ->
ff793acf
SK
46 Y1 = F(X1),
47 Y2 = F(X2),
48 Y3 = F(X3),
49 [Y1, Y2, Y3];
781f182f 50map([X1, X2, X3, X4], F, _, _) ->
ff793acf
SK
51 Y1 = F(X1),
52 Y2 = F(X2),
53 Y3 = F(X3),
54 Y4 = F(X4),
55 [Y1, Y2, Y3, Y4];
781f182f 56map([X1, X2, X3, X4, X5 | Xs], F, RecursionLimit, RecursionCount) ->
ff793acf
SK
57 Y1 = F(X1),
58 Y2 = F(X2),
59 Y3 = F(X3),
60 Y4 = F(X4),
61 Y5 = F(X5),
62 Ys =
781f182f 63 case RecursionCount > RecursionLimit
ff793acf 64 of true -> map_slow(Xs, F)
781f182f 65 ; false -> map (Xs, F, RecursionLimit, RecursionCount + 1)
ff793acf
SK
66 end,
67 [Y1, Y2, Y3, Y4, Y5 | Ys].
68
69
2a81fbac
SK
70%% @doc lists:reverse(map_rev(L, F))
71%% @end
72-spec map_slow([A], fun((A) -> (B))) ->
73 [B].
74map_slow(Xs, F) ->
75 lists:reverse(map_rev(Xs, F)).
76
77
5e20a667
SK
78%% @doc Tail-recursive alternative to lists:map/2, which accumulates and
79%% returns list in reverse order.
c66ddf80
SK
80%% @end
81-spec map_rev([A], fun((A) -> (B))) ->
82 [B].
83map_rev(Xs, F) ->
84 map_rev_acc(Xs, F, []).
85
86-spec map_rev_acc([A], fun((A) -> (B)), [B]) ->
87 [B].
88map_rev_acc([], _, Ys) ->
89 Ys;
90map_rev_acc([X|Xs], F, Ys) ->
91 Y = F(X),
92 map_rev_acc(Xs, F, [Y|Ys]).
93
94
a6244ba2
SK
95-spec unique_preserve_order(t(A)) ->
96 t(A).
97unique_preserve_order(L) ->
17b5d686 98 PrependIfNew =
a6244ba2
SK
99 fun (X, Xs) ->
100 case lists:member(X, Xs)
17b5d686
SK
101 of true -> Xs
102 ; false -> [X | Xs]
a6244ba2
SK
103 end
104 end,
17b5d686 105 lists:reverse(lists:foldl(PrependIfNew, [], L)).
a626cf31
SK
106
107-spec first_match([{Tag, fun((A) -> boolean())}], A) ->
108 hope_option:t(Tag).
109first_match([], _) ->
110 none;
111first_match([{Tag, F} | Tests], X) ->
112 case F(X)
113 of true -> {some, Tag}
114 ; false -> first_match(Tests, X)
115 end.
This page took 0.040362 seconds and 4 git commands to generate.