0
votes

Can anyone tell me where can I find a nice documentation about input and output in Prolog? I need to ask some questions to the users based on some facts and rules. For example:

best_team(bestteam).

And ask in SWI-Prolog: Can you guest what the best team name is?

So the user can write like bestteam and I Prolog answer for example: You are right!

Something like that.

Thanks.

1
I have asked myself this question many times, so I made some doc myself, available at github.David Tonhofer

1 Answers

2
votes

The example shown can be done with the basic I/O routines, write/1, read/1, and nl/0:

best_team(bills).

main :-
    repeat,
    write('Can you guest what the best team name is?'), nl,
    read(X),
    best_team(X),
    write('You are right!'), nl, !.

| ?- main.
Can you guest what the best team name is?
giants.
Can you guest what the best team name is?
bills.
You are right!

yes
| ?-

This can easily be extended to give a "You are wrong!" message for a wrong response. One way would be:

main :-
    repeat,
    write('Can you guest what the best team name is?'), nl,
    read(X),
    (   best_team(X)
    ->  write('You are right!'), nl, !
    ;   write('You are wrong!'), nl, fail
    ).

This will result in:

| ?- main.
Can you guest what the best team name is?
giants.
You are wrong!
Can you guest what the best team name is?
bills.
You are right!

yes
| ?-

If you want to enter input with punctuation, capitalized words, etc, then you'll need to use other predicates. There was a recent question posted on this topic.