2

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?

false
  • 10,264
  • 13
  • 101
  • 209
Rahn
  • 4,787
  • 4
  • 31
  • 57
  • 2
    You pressed Return! Press Space to get the next answer. – false May 08 '16 at 18:45
  • `adjacent(1,3).` should have resulted in `yes`. There's something you didn't do quite right which isn't visible. – lurker May 08 '16 at 19:58
  • @false I make it in repl, but how could get those value when running the program as a script like `swipl -q -f Adjacent.pl -t main`? – Rahn May 09 '16 at 00:01

3 Answers3

1

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.

CapelliC
  • 59,646
  • 5
  • 47
  • 90
0

You need a failure-loop:

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

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

This is a basic programming technique in Prolog. fail/0 will force backtracking, so next adjacent/2 solution is explored (and so on). Second clause to main/0 prevents the loop itself from failure.

Zebollo
  • 1
  • 1
0

after Prolog prints R = 2;, you can press "r", "n", [TAB] or [SPACE] to show the next results. I don't know how that works with write(R). but that is not in the code from the tutorial so I think that's supposed to be the trick