Other things on this site...

MCLD
music
Evolutionary sound
Listen to Flat Four Internet Radio
Learn about
The Molecules of HIV
MCLD
software
Make Oddmusic!
Make oddmusic!

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?

Thursday 19th January 2012 | IT | Permalink
Comments:
Name: diego sevilla
Website: http://neuromancer.inf.um.es/fm
Email: dsevilla art ditec dort um dort es
Date: Thursday 19th January 2012 19:24
No expert here, but for starters, valid with just one element will fail because validone does not accept an empty list as second argument. Adding just 'validone(_,[]).' I get

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

:)

Regards,
diego.
Name: Dan
Date: Friday 20th January 2012 03:11
Thanks! That was the bug! :)

Add your comments:

Name:
Email:
Website:
Comment:
I am a:
Everything is optional - and email addresses will be marmalised to protect you
Creative Commons License
Dan's blog articles may be re-used under the Creative Commons Attribution-Noncommercial-Share Alike 2.5 License. Click the link to see what that means...