Search code examples
prologzebra-puzzle

knowledgment unification in prolog


What I have to do is to unify the possible options and solve the problem with these sentences

  1. The Spaniard lives next to the red house.
  2. The Norwegian lives in the blue house.
  3. An Italian lives in the second house.

This is my attempt but I am getting an error, could someone please help me.

neighborhood(N):-
  length(V,3),
  next(house(_,spaniard), house(red,_), V),
  member(house(blue,norway), V),
  V = [_|house(_,italian)].

Solution

  • You may write a procedure that enforces each of your rules, and then let prolog find the possible ordering of houses that fulfill all those rules:

    neiborhood(Houses):-
     Houses=[House1, Italy, House3], % these are the houses, after rule 3
     Italy=house(_ItalyColor, italy),
     Spain=house(_SpainColor, spain),
     
     % rule 2:
     Norway=house(blue, norway),
     member(House1-House3, [Spain-Norway, Norway-Spain]),
    
     % rule 1:
     append(_, [HouseA, HouseB|_], Houses),
     (HouseA-HouseB=Spain-house(red, _) ; HouseB-HouseA=Spain-house(red, _)).
    

    In this code I assumed when you said that the Spaniard lives next to the red house that it may live "to the left" or "to the right" of that house. Also note that you only mention 2 house colors, so the third one gets unassigned color. Maybe you are missing another rule, possible which is the missing color.

    Sample run:

    ?- neiborhood(Houses).
    Houses = [house(_163550, spain), house(red, italy), house(blue, norway)] ;
    Houses = [house(blue, norway), house(red, italy), house(_163550, spain)] ;
    false.
    

    In both solutions, the Spain house does not have any color assigned.