Search code examples
prologswi-prologdcg

Asking DCG Prolog for an answer


I have a DCG written in prolog which tries to translate a string into simple propositional logic.

The current rules are: + means OR, * means AND, - means NOT

g(or(X,Y)) -->
    f(X),
    "+",
    g(Y).
g(X) -->
    f(X).

f(and(X,Y)) -->
   e(X),
   "*",
   f(Y).
f(X) -->
   e(X).

e(not(X)) -->
   "-",
   d(X).
e(X) -->
   d(X).

d(X)-->
   "(",
   g(X),
   ")".    
d(a)-->
   "a".
d(b)-->
   "b".

However I am having problems with Out of local trace errors.

This code should be correct, but how do I ask Prolog to give and(not(or(a,b)),or(b,not(a))) as an answer to -(a+b) * (b + -a)


Solution

  • your grammar seems fine, but you forgot to handle/skip blanks

    ?- phrase(g(X), `-(a+b)*(b+-a)`).
    X = and(not(or(a, b)), or(b, not(a))) ;
    false.
    

    (note: I've manually removed all blanks, and used SWI-Prolog extensions for list of codes literal.)