如何在代码中执行查询?
例如:
person(abe,instructor).
person(bob,student).
person(cindy,student).
person(david,student).
person(abe,student).
% Like this, but this does not work
% :- person(X,Y).
加载程序后,我可以运行以下查询:person(X,Y)。
如何将此查询作为程序本身的一部分运行,因此一旦程序加载,它将运行查询并输出:
X = abe,
Y = instructor ;
X = bob,
Y = student ;
X = cindy,
Y = student ;
X = david,
Y = student ;
X = abe,
Y = student.
答案 0 :(得分:1)
你可以创建一个新的谓词..这里有两种不同的方式。第一个找到所有人(X,Y),将它们放入AllPeople列表中,然后将其写出来。
第二个是'故障驱动循环',它执行第一个匹配,将其写出来,然后告诉prolog再次尝试,即'fail',这将持续到没有更多匹配,然后匹配第二个谓词同名,以确保谓词最终返回true。
showpeople1 :-
findall(X/Y, person(X,Y), AllPeople),
write(AllPeople).
showpeople2 :-
person(X, Y),
write(X), write(','), write(Y), nl,
fail.
showpeople2 :- true.
?- showpeople1.
[abe/instructor,bob/student,cindy/student,david/student,abe/student]
true.
?- showpeople2.
abe,instructor
bob,student
cindy,student
david,student
abe,student
true.