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.

有帮助吗?

解决方案 2

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.

其他提示

In GNU Prolog you can avoid the final dot when passnig the end_of_term(eof) option to read_term_from_atom. E.g.,:

| ?- 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 an EOF (end of file) is encountered it is considered as the end of the term being read. When reading from an atom, EOF corresponds to the then of the string representation of the atom.

This can simplify things in some situations.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top