|
32 | 32 | -export([
|
33 | 33 | map/2,
|
34 | 34 | nth/2,
|
| 35 | + last/1, |
35 | 36 | member/2,
|
36 | 37 | delete/2,
|
37 | 38 | reverse/1,
|
|
45 | 46 | keytake/3,
|
46 | 47 | foldl/3,
|
47 | 48 | foldr/3,
|
| 49 | + mapfoldl/3, |
48 | 50 | all/2,
|
49 | 51 | any/2,
|
50 | 52 | flatten/1,
|
@@ -90,6 +92,16 @@ nth(1, [H | _T]) ->
|
90 | 92 | nth(Index, [_H | T]) when Index > 1 ->
|
91 | 93 | nth(Index - 1, T).
|
92 | 94 |
|
| 95 | +%%----------------------------------------------------------------------------- |
| 96 | +%% @param L the proper list from which to get the last item |
| 97 | +%% @returns the last item of the list. |
| 98 | +%% @doc Get the last item of a list. |
| 99 | +%% @end |
| 100 | +%%----------------------------------------------------------------------------- |
| 101 | +-spec last(L :: nonempty_list(E)) -> E. |
| 102 | +last([E]) -> E; |
| 103 | +last([_H | T]) -> last(T). |
| 104 | + |
93 | 105 | %%-----------------------------------------------------------------------------
|
94 | 106 | %% @param E the member to search for
|
95 | 107 | %% @param L the list from which to get the value
|
@@ -372,6 +384,24 @@ foldl(Fun, Acc0, [H | T]) ->
|
372 | 384 | Acc1 = Fun(H, Acc0),
|
373 | 385 | foldl(Fun, Acc1, T).
|
374 | 386 |
|
| 387 | +%%----------------------------------------------------------------------------- |
| 388 | +%% @param Fun the function to apply |
| 389 | +%% @param Acc0 the initial accumulator |
| 390 | +%% @param List the list over which to fold |
| 391 | +%% @returns the result of mapping and folding Fun over L |
| 392 | +%% @doc Combine `map/2' and `foldl/3' in one pass. |
| 393 | +%% @end |
| 394 | +%%----------------------------------------------------------------------------- |
| 395 | +-spec mapfoldl(fun((A, Acc) -> {B, Acc}), Acc, [A]) -> {[B], Acc}. |
| 396 | +mapfoldl(Fun, Acc0, List1) -> |
| 397 | + mapfoldl0(Fun, {[], Acc0}, List1). |
| 398 | + |
| 399 | +mapfoldl0(_Fun, {List1, Acc0}, []) -> |
| 400 | + {?MODULE:reverse(List1), Acc0}; |
| 401 | +mapfoldl0(Fun, {List1, Acc0}, [H | T]) -> |
| 402 | + {B, Acc1} = Fun(H, Acc0), |
| 403 | + mapfoldl0(Fun, {[B | List1], Acc1}, T). |
| 404 | + |
375 | 405 | %%-----------------------------------------------------------------------------
|
376 | 406 | %% @equiv foldl(Fun, Acc0, reverse(List))
|
377 | 407 | %% @doc Fold over a list of terms, from right to left, applying Fun(E, Accum)
|
|
0 commit comments