Erlang Central

# Difference between revisions of "Operating on a Series of Integers"

From ErlangCentral Wiki

## Problem

You want to perform an operation on all integers in a certain range.

## Solution

Use the lists:map, lists:foldl, lists:foldr, or lists:foreach functions if you have a known list of (possibly non-contiguous) integers. Otherwise, try a do loop.

For example, to double all entries in a list:

```1> A_list = [1, 2, 5, 7, 9, 10, 108].
[1,2,5,7,9,10,108]
2> lists:map(fun(X) -> 2 * X end, A_list).
[2,4,10,14,18,20,216]
3> lists:foreach(fun(X) -> io:fwrite("~w ", [2 * X]) end, A_List).
2 4 10 14 18 20 216 ok
```

Or, to print all even integers less than 71:

```4> lists:filter(fun (X) -> case X rem 2 of
4>         0 -> true;
4>         _ -> false
4>     end
4> end, lists:seq(0,72,1)).
[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,
32,34,36,38,40,42,44,46,48,50,52,54,56|...]
```

Of course, if you know you want evens, it's easy enough just to do this:

```5> lists:seq(0,72,2).
[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,
32,34,36,38,40,42,44,46,48,50,52,54,56|...]
```

Or, to iterate across all integers from 0 to 71, step 7:

```6> lists:map(fun(X) -> case X >= 71 of
6>         true -> io:fwrite("Done! ~w", [X]);
6>         _ -> io:fwrite("~w ", [X]) end
6> end, lists:seq(0,77,7)).
0 7 14 21 28 35 42 49 56 63 70 Done! 77
```

Erlang forces you into a more functional approach to loops, since it does not provide normal looping constructs of an imperative programming language.

The following code shows each technique, (plus recursion). Here we only print the numbers we generate:

```infancy() ->
io:fwrite("Infancy is: "),
lists:foldl( fun(X,Y) -> io:fwrite("~w ", [X]), Y end,
0, [0,1,2]),
io:nl().

toddling() ->
io:fwrite("Toddling is: "),
lists:foreach( fun(X) -> io:fwrite("~w ", [X]) end, [3, 4]),
io:nl().

childhood() ->
io:fwrite("Childhood is: "),
lists:map( fun(X) -> io:fwrite("~w ", [X]) end,
lists:seq(5,12,1)),
io:nl().
```

The program output looks like:

```1> infancy(), toddling(), childhood().
Infancy is: 0 1 2
Toddling is: 3 4
Childhold is: 5 6 7 8 9 10 11 12
```