Prolog: Zebra Puzzle

advertisement
Prolog: Zebra Puzzle
Zebra Puzzle
1)
2)
3)
4)
5)
6)
7)
8)
9)
10)
11)
12)
13)
14)
15)
There are five houses.
The Englishman lives in the red house.
The Spaniard owns the dog.
Coffee is drunk in the green house.
The Ukrainian drinks tea.
The green house is immediately to the right of the ivory house.
The Old Gold smoker owns snails.
Kools are smoked in the yellow house.
Milk is drunk in the middle house.
The Norwegian lives in the first house.
The man who smokes Chesterfields lives in the house next to the man with
the fox.
Kools are smoked in the house next to the house where the horse is kept.
The Lucky Strike smoker drinks orange juice.
The Japanese smokes Parliaments.
The Norwegian lives next to the blue house.
Who owns the zebra?
— Life International, December 17, 1962
house(C, N, P, D, S)
• We define house(C, N, P, D, S) predicate which signify
the following information.
C: the color of the house
N: the nationality of the resident
P: the resident's pet
D: the resident's drink
S: the resident's cigarette
• With the aid of the anonymous variable '_', we can
represent the fact
"The Englishman lives in the red house."
as a Prolog statement house(red, englishman, _, _, _).
next_to(X, Y, List)
• The next_to(X, Y, List) rule is true if the
elements X and Y are adjacent in the List.
next_to(X, Y, List) :- is_right(X, Y, List).
next_to(X, Y, List) :- is_right(Y, X, List).
is_right(L, R, [L | [R | _]])
• is_right(L, R, [L | [R | _]]) is true if the
element L comes first in the list and the
element R is at the second position.
is_right(L, R, [L | [R | _]]).
is_right(L, R, [_ | Rest]) :- is_right(L, R, Rest).
Fact
owns_zebra(Street, Who) :Street = [_House1, _House2, _House3, _House4, _House5], member(house(red, englishman, _, _, _), Street),
member(house(_, spaniard, dog, _, _), Street),
member(house(green, _, _, coffee, _), Street),
member(house(_, ukrainian, _, tea, _), Street),
is_right(house(green,_,_,_,_),
house(ivory,_,_,_,_), Street),
member(house(_, _, snails, _, old_gold), Street),
member(house(yellow, _, _, _, kools), Street),
[_, _, house(_, _, _, milk, _), _, _] = Street,
[house(_, norwegian, _, _, _) | _] = Street,
next_to(house(_, _, _, _, chesterfields),
house(_, _, fox, _, _), Street),
next_to(house(_, _, _, _, kools),
house(_, _, horse, _, _), Street),
member(house(_, _, _, orange_juice, lucky_strike), Street),
member(house(_, japanese, _, _, parliaments), Street),
next_to(house(_, norwegian, _, _, _),
house(blue, _, _, _, _), Street),
member(house(_, Who, zebra, _, _), Street).
Execution
?- owns_zebra(Street, Who).
Street = [house(yellow, norwegian, fox, _G320, kools), house(blue, ukrainian,
horse, tea, chesterfields), house(red, englishman, snails, milk, old_gold),
house(green, japanese, zebra, coffee, parliaments), house(ivory, spaniard,
dog, orange_juice, lucky_strike)],
Who = japanese
Download