Search code examples
prolog

Nested for loop in prolog


I'm quite new to Prolog so im not sure how this can be done.

I'm trying to create a nested for loop that outputs the three variables on each line.

I'm trying to get an output that loops like the following:

SWI-Prolog

?- out(A, B, C).
A = 1, B = 1, C = 1 (Next)
A = 1, B = 1, C = 2 (Next)
A = 1, B = 2, C = 1 (Next)

A = 1, B = 2, C = 2 (Next)
A = 2, B = 1, C = 1 (Next)
A = 2, B = 1, C = 2 (Next)

A = 2, B = 2, C = 1 (Next)
A = 2, B = 2, C = 2 (Next)

it needs to have a custom range

in Python it would look like this

for i in range(1,3):
    for j in range(1,3):
        for k in range(1,3):
        print(i, j, k)

Solution

  • out(A, B, C) :-
        maplist(between(1, 2), [A, B, C]).
    

    Result:

    ?- out(A, B, C).
    A = B, B = C, C = 1 ;
    A = B, B = 1,
    C = 2 ;
    A = C, C = 1,
    B = 2 ;
    A = 1,
    B = C, C = 2 ;
    A = 2,
    B = C, C = 1 ;
    A = C, C = 2,
    B = 1 ;
    A = B, B = 2,
    C = 1 ;
    A = B, B = C, C = 2.