8 [ unique_preserve_order/1
10 , map/3 % Tunable recursion limit
13 , map_result/2 % Not tail-recursive
18 -define(DEFAULT_RECURSION_LIMIT, 1000).
23 %% @doc Tail-recursive equivalent of lists:map/2
25 -spec map([A], fun((A) -> (B))) ->
28 map(Xs, F, ?DEFAULT_RECURSION_LIMIT).
30 -spec map([A], fun((A) -> (B)), RecursionLimit :: non_neg_integer()) ->
32 map(Xs, F, RecursionLimit) ->
33 map(Xs, F, RecursionLimit, 0).
40 map([X1, X2], F, _, _) ->
44 map([X1, X2, X3], F, _, _) ->
49 map([X1, X2, X3, X4], F, _, _) ->
55 map([X1, X2, X3, X4, X5 | Xs], F, RecursionLimit, RecursionCount) ->
62 case RecursionCount > RecursionLimit
63 of true -> map_slow(Xs, F)
64 ; false -> map (Xs, F, RecursionLimit, RecursionCount + 1)
66 [Y1, Y2, Y3, Y4, Y5 | Ys].
68 %% @doc lists:reverse(map_rev(L, F))
70 -spec map_slow([A], fun((A) -> (B))) ->
73 lists:reverse(map_rev(Xs, F)).
75 %% @doc Tail-recursive alternative to lists:map/2, which accumulates and
76 %% returns list in reverse order.
78 -spec map_rev([A], fun((A) -> (B))) ->
81 map_rev_acc(Xs, F, []).
83 -spec map_rev_acc([A], fun((A) -> (B)), [B]) ->
85 map_rev_acc([], _, Ys) ->
87 map_rev_acc([X|Xs], F, Ys) ->
89 map_rev_acc(Xs, F, [Y|Ys]).
91 -spec map_result([A], fun((A) -> (hope_result:t(B, C)))) ->
92 hope_result:t([B], C).
95 map_result([X | Xs], F) ->
98 case map_result(Xs, F)
101 ; {error, _}=Error ->
104 ; {error, _}=Error ->
108 -spec unique_preserve_order(t(A)) ->
110 unique_preserve_order(L) ->
113 case lists:member(X, Xs)
118 lists:reverse(lists:foldl(PrependIfNew, [], L)).
120 -spec first_match([{Tag, fun((A) -> boolean())}], A) ->
122 first_match([], _) ->
124 first_match([{Tag, F} | Tests], X) ->
126 of true -> {some, Tag}
127 ; false -> first_match(Tests, X)
130 %% @doc Divide list into sublists of up to a requested size + a remainder.
131 %% Order unspecified. Size < 1 raises an error:
132 %% `hope_list__divide__size_must_be_a_positive_integer'
134 -spec divide([A], pos_integer()) ->
136 divide(_, Size) when Size < 1 orelse not is_integer(Size) ->
138 % A: For N < 0, what does it mean to have a negative-sized chunk?
139 % For N = 0, we can imagine that a single chunk is an empty list, but,
140 % how many such chunks should we produce?
141 % This is pretty-much equivalnet to the problem of deviding something by 0.
142 error(hope_list__divide__size_must_be_a_positive_integer);
145 divide([X1 | Xs], MaxChunkSize) ->
147 fun (X2, {Chunk, Chunks, ChunkSize}) when ChunkSize >= MaxChunkSize ->
148 {[X2], [Chunk | Chunks], 1}
149 ; (X2, {Chunk, Chunks, ChunkSize}) ->
150 {[X2 | Chunk], Chunks, ChunkSize + 1}
152 {Chunk, Chunks, _} = lists:foldl(MoveIntoChunks, {[X1], [], 1}, Xs),