prologcrosswordprolog-dif

Force Prolog to choose unique values of variables


OK I am new to Prolog, so excuse me if this is something trivial, but I can't seem to find a proper elegant answer to this. I am trying to work out the exercise here on learnprolognow.org, exercise 2.4 (the crossword).

The exercise provides these facts:

   word(astante,  a,s,t,a,n,t,e). 
   word(astoria,  a,s,t,o,r,i,a). 
   word(baratto,  b,a,r,a,t,t,o). 
   word(cobalto,  c,o,b,a,l,t,o). 
   word(pistola,  p,i,s,t,o,l,a). 
   word(statale,  s,t,a,t,a,l,e).

And the solution I came up with to solve the crossword placement of each word is this:

crossword(V1, V2, V3, H1, H2, H3) :-
   word(V1, V1a, V1bH1b, V1c, V1dH2b, V1e, V1fH3b, V1g), 
   word(V2, V2a, V2bH1d, V2c, V2dH2d, V2e, V2fH3d, V2g), 
   word(V3, V3a, V3bH1f, V3c, V3dH2f, V3e, V3fH3f, V3g), 
   word(H1, H1a, V1bH1b, H1c, V2bH1d, H1e, V3bH1f, H1g), 
   word(H2, H2a, V1dH2b, H2c, V2dH2d, H2e, V3dH2f, H2g), 
   word(H3, H3a, V1fH3b, H3c, V2fH3d, H3e, V3fH3f, H3g).

With V1a to V1g etc. being the characters of each word, and the V1bH1b to V3fH3f being the characters in common between words in the crossword.

The solution seems to work, however the result is producing duplicate values, with the first result being:

?- crossword(V1, V2, V3, H1, H2, H3).
V1 = astante,
V2 = baratto,
V3 = statale,
H1 = astante,
H2 = baratto,
H3 = statale .

How can I force Prolog to have V1 \= V2 \= V3 \= H1 \= H2 \= H3 ? If I do them individually one by one I will need 120 permutations, so there must be a quicker way, and this is a beginners exercise so I must be missing something.

I found this similar question, but the answers provided seem so complicated, I hope there is a simpler way. I am using swi-prolog on Ubuntu, just in case it matters.

Thanks.


Solution

  • Use alldif/1 defined like so:

    alldif([]).
    alldif([E|Es]) :-
       maplist(dif(E), Es),
       alldif(Es).
    

    Which can be used even for the most general query:

    ?- alldif(Es).
       Es = []
    ;  Es = [_A]
    ;  Es = [_A,_B], dif(_A,_B)
    ;  Es = [_A,_B,_C],
       dif(_A,_B), dif(_A,_C),
       dif(_B,_C)
    ;  Es = [_A,_B,_C,_D],
       dif(_A,_B), dif(_A,_C), dif(_A,_D),
       dif(_B,_C), dif(_B,_D),
       dif(_C,_D)
    ;  ... .
    

    The meaning of the goal maplist(dif(E),Es) is best understood by looking at the answers:

    ?- maplist(dif(E),Es).
       Es = []
    ;  Es = [_A], dif(E,_A)
    ;  Es = [_A,_B], dif(E,_A), dif(E,_B)
    ;  Es = [_A,_B,_C], dif(E,_A), dif(E,_B), dif(E,_C)
    ;  ... .
    

    That is, Es is a list of elements that are all different to E. The goal maplist(dif(E),[A,B,C]) combines the first element (in this case dif(E)) with each element of the list. Thus dif(E,A), dif(E,B), dif(E,C).