Writing a simple "process of elimination" Prolog code using DCGs

218 views Asked by At

I have simplified a more complex problem to the following: there are three houses on a street with three different colours (no colour repeated); red, blue, green. Write a program using DCGs to simulate all permutations/possibilities. My code won't run and I'm struggling to see why. Any corrections would really help.

s --> h(X), h(Y), h(Z), X\=Y, X\=Z, Y\=Z.

h(X) --> Col(X).

Col(X) --> [red].
Col(X) --> [blue].
Col(X) --> [green].
2

There are 2 answers

0
CapelliC On

You are (also) forgetting to 'return' the value from the leaves:

...
col(red)-->[red].
...

With a so small dataset, it's tempting to hardcode the permutation:

s --> r,g,b ; r,b,g ; g,r,b ; b,r,g ; g,b,r ; b,g,r.
r --> [red].
g --> [green].
b --> [blue].
2
false On

s/Col/col/

And then, you are using within s//0 Prolog goals in the place of non-terminals. That does not work, you need to "escape" them with {}//0 like so

s -->h(X),h(Y),h(Z),{X\=Y,X\=Z,Y\=Z}.

But I would rather write:

s --> {dif(X,Y), dif(Y,Z), dif(X,Z)}, h(X),h(Y),h(Z).

In this manner Prolog performs all the bookkeeping for you.

If we're at it. Don't forget to call the non-terminal via phrase/2. Thus:

?- phrase(s, L).