How to print unification results when using a prolog script?
I am using a prolog script to execute all requests, the code looks like this:
:- initialization(run).
writeln(T) :- write(T), nl.
queryAll :-
forall(query(Q), (Q ->
writeln('yes':Q) ;
writeln('no ':Q))).
run :-
queryAll,
halt.
query( (1,2,3) = (X,Y,Z) ).
the problem is it queryAll
will only print "yes" or "no" as long as I want to see the results of the merge, for example:
X = 1
Y = 2
Z = 3
How to do this in the prologue? Thanks in advance.
source to share
here's a sample of built-in gprologs that might be helpful to create a better experience for your clients:
| ?- read_term_from_atom('X+Y = 1+2.', T, [variable_names(L)]). L = ['X'=A,'Y'=B] T = A+B=1+2 yes | ?- read_term_from_atom('X+Y = 1+2.', T, [variable_names(L)]),call(T). L = ['X'=1,'Y'=2] T = 1+2=1+2
Note that you must change the content of the / 1: request instead of
query( (1,2,3) = (X,Y,Z) ).
it should be
query( '(1,2,3) = (X,Y,Z).' ). % note the dot terminated atom
and then the loop could be for example
queryAll :-
forall(query(Q),
( read_term_from_atom(Q, T, [variable_names(L)]),
( T -> writeln('yes':L) ; writeln('no ':Q) )
)).
I am getting a hint from this answer.
source to share
In GNU Prolog, you can escape the last point when you pass a parameter end_of_term(eof)
to read_term_from_atom
.. For example,
| ?- read_term_from_atom('X+Y = 1+2', T, [variable_names(L),end_of_term(eof)]).
L = ['X'=A,'Y'=B]
T = (A+B=1+2)``
This means that when EOF (end of file) is encountered, it is considered the end of the read term. When reading from an atom, EOF then corresponds to the lowercase representation of the atom.
This can make things easier in some situations.
source to share