Search code examples
prologgnu-prologunification

How can I print unification results when using prolog script?


I'm using prolog script to do all queries, the code goes like:

:- 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 that queryAll will only print "yes" or "no" while I want to see the unification results like:

X = 1
Y = 2
Z = 3

How to do this in prolog? Thanks in advance.


Solution

  • here a sample of gprolog builtins that could be useful to build a better experience for your customers:

    | ?- 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 should change the query/1 content: instead of

    query( (1,2,3) = (X,Y,Z) ).
    

    should be

    query( '(1,2,3) = (X,Y,Z).' ). % note the dot terminated atom
    

    and then the loop could be, for instance

    queryAll :-
        forall(query(Q), 
            ( read_term_from_atom(Q, T, [variable_names(L)]),
              ( T -> writeln('yes':L) ; writeln('no ':Q) )
            )).
    

    I get the hint from this answer.