% comment the next two lines out when testing - put back in to submit
:- initialization(q1).
:- initialization(q2).
:- initialization(q3).
:- initialization(end).
% FACTS.
mammal(kitty).
mammal(ratatat).
mammal(fido).
claws(kitty).
tail(ratatat).
bestfriend(fido).
feathers(tweety).
% 9 RULES.
% If X is a mammal then X has fur.
fur(X) :- mammal(X).
% If X has fur and X has a tail then X is a rat.
rat(X) :- fur(X),tail(X).
% If X has claws and X has fur then X is a cat.
cat(X) :- claws(X),fur(X).
% If X is a cat then X meows.
meows(X) :- cat(X).
% If X has feathers then X is a bird.
bird(X) :- feathers(X).
% If X is a bestfriend and X has fur then X is a dog.
dog(X) :- bestfriend(X),fur(X).
% If X is a dog and Y meows then X likes Y.
likes(X,Y) :- dog(X),meows(Y).
% If X is a cat and Y is a bird then X likes Y.
likes(X,Y) :- cat(X),bird(Y).
% If X is a cat and Y is a rat then X likes Y.
likes(X,Y) :- cat(X),rat(Y).
writeln(T) :- write(T), nl.
max(X,Y,Z) :-
X > Y,
X > Z,
write(X).
max(X,Y,Z) :-
X > Y,
write(Z).
max(_,Y,Z) :-
Y > Z,
write(Y).
max(_,_,Z) :-
write(Z).
moves(N,R) :-
N = 0, R is 0.
moves(N,R) :-
N = 1, R is 1.
moves(N,R) :-
N > 1, T1 is N - 1, T2 is N-1, moves(T1,R1), moves(T2,R2), R is R1 + R2 + 1.
% QUERY. Uncomment after you have written all predicates.
q1 :- writeln('Who likes whom?'),
findall(X, (likes(X,Y), format('~w ~w~n',[X,Y])),_).
q2 :- write('Move cnt for 5: '),
findall(X, (moves(5,X), format('~w' ,[X])),_).
q3 :-nl, write( 'Max(7,3,9)? '),
findall(X, (max(7,3,9), format('~w ~n' ,[X])),_).
end :- writeln('done.'), halt.
输出:
谁喜欢谁?
fido kitty
kitty tweety
kitty ratatat
移动cnt为5:31
马克斯(7,3,9)? 9_13< ----为什么打印和下划线13?
9_13< ---也为什么再次打印这一行?
完成。
不确定为什么它的打印方式是任何信息将不胜感激!我认为它与我的q3查询有关,但我一直在搞乱它并且无法弄明白,谢谢你们!
答案 0 :(得分:1)
q3与q1,q2的共同点是findall / 3的一个不寻常的用法(我认为你应该使用forall / 2,真的)。与其他2个查询不同,q3输出无界变量(X不会出现在findall 目标中),并且它会执行2次,因为max / 3会成功2次。这是q3相关的跟踪,获得(在swipl中)添加指令:- initialization((leash(-all),trace)).
。在gprolog中,它是:- initialization((leash(none),trace)).
Call: (20) q3
Call: (21) nl
Exit: (21) nl
Call: (21) write('Max(7,3,9)? ')
Max(7,3,9)?
Exit: (21) write('Max(7,3,9)? ')
^ Call: (21) findall(_G1900, (max(7, 3, 9), format('~w ~n', [_G1900])), _G1912)
Call: (27) max(7, 3, 9)
Call: (28) 7>3
Exit: (28) 7>3
Call: (28) 7>9
Fail: (28) 7>9
Redo: (27) max(7, 3, 9)
Call: (28) 7>3
Exit: (28) 7>3
Call: (28) write(9)
9
Exit: (28) write(9)
Exit: (27) max(7, 3, 9)
^ Call: (27) format('~w ~n', [_G1900])
_G1900
^ Exit: (27) format('~w ~n', [_G1900])
Redo: (27) max(7, 3, 9)
Call: (28) 3>9
Fail: (28) 3>9
Redo: (27) max(7, 3, 9)
Call: (28) write(9)
9
Exit: (28) write(9)
Exit: (27) max(7, 3, 9)
^ Call: (27) format('~w ~n', [_G1900])
_G1900
^ Exit: (27) format('~w ~n', [_G1900])
^ Exit: (21) findall(_G1900, user: (max(7, 3, 9), format('~w ~n', [_G1900])), [_G1923, _G1920])
Exit: (20) q3