Skipping an Element in List Processing

From Erlang Community

(Difference between revisions)
Revision as of 03:52, 13 October 2006 (edit)
Ayrnieu (Talk | contribs)
m (typo)
← Previous diff
Current revision (00:47, 15 October 2006) (edit) (undo)
Ayrnieu (Talk | contribs)
m (typo in category)
 
Line 37: Line 37:
</code> </code>
-[[Category:Cookbook]][[Category:ListRecipes]]+[[Category:CookBook]][[Category:ListRecipes]]

Current revision

[edit] Problem

You have a simple function and a familiar list operation, but you want to skip certain elements -- either because they match a criteria, or because of some reason that comes up within your function. You wish that you could return 'skip this element' to the list operation, or that you had an iterative continue(), next() such directive.

[edit] Solution

A partial solution could use lists:filter/2 to remove unacceptable elements:

frob(L) ->
    L1 = lists:filter(fun (0) -> false; (_) -> true end, L),
    lists:map(fun frob_elem/1, L1).

This solution fails, however, in that it relies on easy, and stateless, determination of unacceptable elements. A better solution would use lists:foldl/3 or lists:foldr/3 :

frob(L) ->
    lists:foldr(fun (0,RHS) -> RHS;
                    (LHS,RHS) -> [frob_elem(LHS)|RHS]
                end, [], L).

Of course, in this case where you build a list, you can also use a list comprehension:

frob(L) -> [frob_elem(X) || X <- L, X /= 0].
Erlang/OTP Projects
Personal tools