0

I am doing a prolog practice which is taken from this.

What I want to do now is to change the input and output way of the program.
I need to execute the program by typing this in the console:

goldbach(100, L).

just for example, and I need to press [;] to show next result when previous one is printed on the screen.

L = [3, 97];
L = [11, 89];
L = ....

However, what I want to make is like below:

Input a number:100.
L = [3, 97].
L = [11, 89].
.....

That is the program will print "Input a number:" first and read your input, then automatically print out all possible result.

I have read sections about read() and write, but I get fail when I add these:

read_gold :-
  write('Input a number:'),
  read(X),
  write(goldbach(X, L)).

How can I fix my code to make the program to achieve the input and output that I want? Thanks for answering.

false
  • 10,264
  • 13
  • 101
  • 209
Limoncool
  • 5
  • 4
  • You want to modify or reimplement the toplevel. Definitely, too complex for a beginner. – false May 27 '17 at 20:41
  • You can't `write(goldbach(X, L))` to get the results of querying `goldbach(X, L)`. Predicates don't return solutions as functions return values. – lurker May 27 '17 at 20:47

1 Answers1

2

Something like this will do literally what you're asking for, although it's not normally how one uses Prolog queries and solutions.

read_gold :-
  write('Input a number:'),
  read(X),
  show_results(goldbach(X)).

show_results(Query) :-
  call(Query, L),
  write('L = '), write(L), write('.'), nl,
  fail.
show_results(_).

A cleaner way to collect all of the solutions in one go is to list them using findall/3:

read_gold(Solutions) :-
  write('Input a number:'),
  read(X),
  findall(L, goldbach(X, L), Solutions).

Or, without explicitly prompting:

read_gold(X, Solutions) :-
  findall(L, goldbach(X, L), Solutions).

And query it as, for example:

?- read_gold(100, Solutions).
Solutions = [[3, 97], [11,89], ...]
lurker
  • 56,987
  • 9
  • 69
  • 103
  • Using`write/1` for writing terms is quite problematic. Rather use `writeq/1` – false May 27 '17 at 21:34
  • Thanks for your answering. Now I know that I should read about query. It is a good and important thing to solve most of the problems. – Limoncool May 28 '17 at 05:35