Erlang Central

Skipping an Element in List Processing

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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).
<code>

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

<code>
frob(L) -> [frob_elem(X) || X <- L, X /= 0].
```