1 Feb 2012 danstowell   » (Journeyer)

Learning prolog, eight queens

I'm following the "7 languages in 7 weeks" book. This week, PROLOG! However, I'm failing on this task: solve the eight queens puzzle in prolog. Why does this fail:

      queens(List) :-
            List = [Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8],
            valid(List).

    valid([]).
    valid([Head|Tail]) :-
            validone(Head,Tail),
            valid(Tail).

    validone(One,[Head|[]]) :-
            pairok(One, Head).
    validone(One,[Head|Tail]) :-
            pairok(One, Head),
            validone(One, Tail).

    pairok((X1, Y1), (X2, Y2)) :-
            Range = [1,2,3,4,5,6,7,8],
            member(X1, Range),
            member(Y1, Range),
            member(X2, Range),
            member(Y2, Range),
            (X1 =\= X2),
            (Y1 =\= Y2),
            (X1+Y1 =\= X2+Y2),
            (X1-Y1 =\= X2-Y2).

I load it in gprolog using

         ['8queens'].

then I ask it to find me the eight unknowns (A through to H) by executing this:

         queens([(1,A),(2,B),(3,C),(4,D),(5,E),(6,F),(7,G),(8,H)]).

What it should do (I think) is suggest a set of values that the unknowns can take. What it does instead is say:

         no

(which means it thinks there are no possible solutions.) Anyone spot my error?

Syndicated 2012-01-19 17:57:30 from Dan Stowell

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!