Erlang Central

Difference between revisions of "Skipping an Element in List Processing"

From ErlangCentral Wiki

(add recipe)
 
m (typo in category)
(One intermediate revision by one user not shown)
Line 28:Line 28:
 
                     (LHS,RHS) -> [frob_elem(LHS)|RHS]
 
                     (LHS,RHS) -> [frob_elem(LHS)|RHS]
 
                 end, [], L).
 
                 end, [], L).
<code>
+
</code>
  
 
Of course, in this case where you build a list, you can also use a
 
Of course, in this case where you build a list, you can also use a
Line 37:Line 37:
 
</code>
 
</code>
  
[[Category:Cookbook]][[Category:ListRecipes]]
+
[[Category:CookBook]][[Category:ListRecipes]]

Revision as of 00:47, 15 October 2006

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.

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].