For in Erlang

Erlang provides several ways to implement looping constructs. Here are some basic types of loops in Erlang.

-module(for_example).
-export([main/0]).

main() ->
    % The most basic type, with a single condition.
    loop_until(1),

    % A classic initial/condition/after loop.
    loop_with_index(0),

    % Another way of accomplishing the basic "do this N times" iteration.
    lists:foreach(fun(I) ->
        io:format("range ~p~n", [I])
    end, lists:seq(0, 2)),

    % Infinite loop with a break condition
    loop_with_break(),

    % Loop with continue-like behavior
    loop_with_continue(lists:seq(0, 5)).

% Basic loop with a condition
loop_until(I) when I =< 3 ->
    io:format("~p~n", [I]),
    loop_until(I + 1);
loop_until(_) -> ok.

% Loop with an index
loop_with_index(J) when J < 3 ->
    io:format("~p~n", [J]),
    loop_with_index(J + 1);
loop_with_index(_) -> ok.

% Loop with break condition
loop_with_break() ->
    io:format("loop~n"),
    ok.

% Loop with continue-like behavior
loop_with_continue([]) -> ok;
loop_with_continue([N|Rest]) ->
    case N rem 2 of
        0 -> loop_with_continue(Rest);
        1 ->
            io:format("~p~n", [N]),
            loop_with_continue(Rest)
    end.

To run the program, save it as for_example.erl and use the Erlang shell:

$ erl
1> c(for_example).
{ok,for_example}
2> for_example:main().
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In Erlang, loops are typically implemented using recursion. The loop_until/1 and loop_with_index/1 functions demonstrate this approach. The lists:foreach/2 function provides a way to iterate over a list, similar to the range-based for loop in other languages.

Erlang doesn’t have traditional break or continue statements. Instead, you can use pattern matching and recursion to achieve similar behavior. The loop_with_break/0 function shows how to implement a single-iteration loop, while loop_with_continue/1 demonstrates how to skip iterations based on a condition.

We’ll see some other looping constructs later when we look at list comprehensions, higher-order functions, and other data structures.