prologprolog-toplevel

Prolog: get all possible values of a variable


I'm Following Prolog Tutorial 2.1.

Program

adjacent(1, 2).
adjacent(1, 3).
adjacent(1, 4).

main:-
    adjacent(1, R),
    write(R).

prints 2.

But it supposes to print a list of possible values according to the tutorial:

?- adjacent(1,2). 
yes 
?- adjacent(1,3). 
no 
?- adjacent(1,R). 
R = 2 ; 
R = 3 ; 
R = 4 ; 
no

I try again in repl only to get the same result:

?- adjacent(1, R).
R = 2 .

How could I get/print a list of possible values of a variable?


Solution

  • In swipl, library(apply) is - by default - autoloaded, so you can write

    main:-
        forall(adjacent(1, R), (write(R),nl)).
    

    note: Action is a conjuction, just for to illustrate the proper syntax required. For any practical purpose, main :- forall(adjacent(1, R), writeln(R)). could be better.