Difference between revisions of "Skipping an Element in List Processing"
From ErlangCentral Wiki
m (typo in category)
|Line 37:||Line 37:|
Revision as of 00:47, 15 October 2006
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.
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].