For in Prolog

Prolog offers several ways to implement loops and iterations. Here are some basic types of loops in Prolog.

% The most basic type, with a single condition.
loop_basic(I) :-
    I =< 3,
    writeln(I),
    I1 is I + 1,
    loop_basic(I1).

loop_basic(1).

% A classic initial/condition/after loop.
loop_classic(J) :-
    between(0, 2, J),
    writeln(J).

% Another way of accomplishing the basic "do this N times" iteration.
loop_range(N) :-
    between(0, 2, I),
    format('range ~w~n', [I]),
    N is I + 1.

% Loop without a condition will repeat until a condition is met.
loop_infinite :-
    writeln('loop'),
    !.

% You can also use cuts to control the flow of the loop.
loop_continue(N) :-
    N < 6,
    (   N mod 2 =:= 0
    ->  N1 is N + 1,
        loop_continue(N1)
    ;   writeln(N),
        N1 is N + 1,
        loop_continue(N1)
    ).
loop_continue(_).

% Main predicate to run all examples
main :-
    loop_basic(1),
    loop_classic(_),
    loop_range(_),
    loop_infinite,
    loop_continue(0).

To run the program, you can save it in a file (e.g., for_loops.pl) and use a Prolog interpreter. Here’s an example of how to run it using SWI-Prolog:

$ swipl -s for_loops.pl -g main -t halt
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In Prolog, loops are typically implemented using recursion. The loop_basic/1 predicate demonstrates a simple recursive loop. The loop_classic/1 uses the between/3 predicate to iterate over a range of values.

The loop_range/1 predicate shows another way to iterate over a range, similar to the range-based for loop in other languages.

The loop_infinite/0 predicate demonstrates an “infinite” loop that’s immediately cut short with the ! (cut) operator.

Finally, the loop_continue/1 predicate shows how to implement a loop with a continue-like behavior using conditional statements and recursion.

These examples demonstrate various ways to achieve looping behavior in Prolog, which uses a different paradigm compared to imperative languages. The logic and flow control in Prolog are based on predicate success or failure and backtracking, rather than explicit loop constructs.