|
50 | 50 | find/2, |
51 | 51 | filter/2, |
52 | 52 | fold/3, |
| 53 | + foreach/2, |
53 | 54 | map/2, |
54 | 55 | merge/2, |
55 | 56 | remove/2, |
@@ -335,6 +336,33 @@ fold(_Fun, _Init, Map) when not is_map(Map) -> |
335 | 336 | fold(_Fun, _Init, _Map) -> |
336 | 337 | error(badarg). |
337 | 338 |
|
| 339 | +%%----------------------------------------------------------------------------- |
| 340 | +%% @param Fun function to call with every key-value pair |
| 341 | +%% @param MapOrIterator the map or map iterator over which to iterate |
| 342 | +%% @returns `ok' |
| 343 | +%% @doc Iterate over the entries in a map. |
| 344 | +%% |
| 345 | +%% This function takes a function used to iterate over all entries in a map. |
| 346 | +%% |
| 347 | +%% This function raises a `badmap' error if `Map' is not a map or map iterator, |
| 348 | +%% and a `badarg' error if the input function is not a function. |
| 349 | +%% @end |
| 350 | +%%----------------------------------------------------------------------------- |
| 351 | +-spec foreach( |
| 352 | + Fun :: fun((Key :: key(), Value :: value()) -> any()), |
| 353 | + MapOrIterator :: map_or_iterator() |
| 354 | +) -> ok. |
| 355 | +foreach(Fun, Map) when is_function(Fun, 2) andalso is_map(Map) -> |
| 356 | + iterate_foreach(Fun, maps:next(maps:iterator(Map))); |
| 357 | +foreach(Fun, [Pos | Map] = Iterator) when |
| 358 | + is_function(Fun, 2) andalso is_integer(Pos) andalso is_map(Map) |
| 359 | +-> |
| 360 | + iterate_foreach(Fun, maps:next(Iterator)); |
| 361 | +foreach(_Fun, Map) when not is_map(Map) -> |
| 362 | + error({badmap, Map}); |
| 363 | +foreach(_Fun, _Map) -> |
| 364 | + error(badarg). |
| 365 | + |
338 | 366 | %%----------------------------------------------------------------------------- |
339 | 367 | %% @param Fun the function to apply to every entry in the map |
340 | 368 | %% @param Map the map to which to apply the map function |
@@ -463,6 +491,13 @@ iterate_fold(Fun, {Key, Value, Iterator}, Accum) -> |
463 | 491 | NewAccum = Fun(Key, Value, Accum), |
464 | 492 | iterate_fold(Fun, maps:next(Iterator), NewAccum). |
465 | 493 |
|
| 494 | +%% @private |
| 495 | +iterate_foreach(_Fun, none) -> |
| 496 | + ok; |
| 497 | +iterate_foreach(Fun, {Key, Value, Iterator}) -> |
| 498 | + _ = Fun(Key, Value), |
| 499 | + iterate_foreach(Fun, maps:next(Iterator)). |
| 500 | + |
466 | 501 | %% @private |
467 | 502 | iterate_map(_Fun, none, Accum) -> |
468 | 503 | Accum; |
|
0 commit comments