联合(Unification)
变量与任何项目: 变量可以与任何项目绑定,其中也包括变量
原始项目与原始项目: 两个原始项目(原子或整数)只有当它们相同时才能联合。
结构与结构: 如果两个结构的每个相应的参数能联合,那么这两个结构可以联合。
1 ?- (1,2,3)=(X,Y,Z).
X = 1,
Y = 2,
Z = 3.
2 ?- (1,2,3)=(X,X,Z).
false.
3 ?- (1,1,3)=(X,X,Z).
X = 1,
Z = 3.
4 ?- (1,X,3)=(X,1,Z).
X = 1,
Z = 3.
5 ?- (1,X,3)=(X,2,Z).
false.
1 ?- (1,2,X)=(1,2,(3,4,5)).
X = (3, 4, 5).
2 ?- (1,2,X)=(1,2,(3,4,Y)),Y=5.
X = (3, 4, 5),
Y = 5.
%_表示不关心匹配内容
3 ?- (1,2,X,Y,7)=(1,2,(3,4,5),6,_).
X = (3, 4, 5),
Y = 6.
4 ?- X = Y, Y = hi, write(X).
hi
X = Y, Y = hi.
%swipl -s objs.pl
%Hansen
%room
room(kitchen).
%objects and location
%object(Name, Color, Size, Weight).
location(object(candle, red, small, 1), kitchen).
location(object(apple, red, small, 1), kitchen).
location(object(apple, green, small, 1), kitchen).
location(object(table, blue, big, 50), kitchen).
%current room
here(kitchen).
%can take something?
can_take(Thing) :-
here(Room),
location(object(Thing, _, small, _), Room).
can_take(Thing) :-
here(Room),
location(object(Thing, _, big, _), Room),
write('The '), write(Thing),
write(' is too big to carry.'), nl,
fail.
can_take(Thing) :-
here(Room),
not(location(object(Thing, _, _, _), Room)),
write('There is no '), write(Thing), write(' here.'), nl,
fail.
%out put the weight
write_weight(1) :- write('1 pound').
write_weight(W) :- W > 1, write(W), write(' pounds').
%list all things in a room
list_things(Place) :-
location(object(Thing, Color, Size, Weight), Place),
write('A '),write(Size),tab(1),
write(Color),tab(1),
write(Thing), write(', weighing '),
write_weight(Weight), nl,
fail.