我認爲這只是一個基本的遞歸問題 - 如何遍歷列表,並在頭上使用模式匹配。如果是的話,這應該做
% case 1 - end recursion
listiter([]).
% case 2 - list head obj2 matches
listiter([obj2(Obj_2_Value)|T]) :-
write(Obj_2_Value), nl,
listiter(T).
% case 3 - case 2 failed, just recurse, ignoring head
listiter([_|T]) :-
listiter(T).
在你的「真實」的代碼,替換了「寫入/ NL」不管你要真的做OBJ2()的值謂詞。
?listiter([obj1(brown), obj2(hello), obj3(fred), obj2(stack), obj4(bun), obj2(overflow)]).
hello
stack
overflow
true .
或更短的方式,使用內置MAPLIST/1:列出的
% match if item is obj2()
dosomething(obj2(Obj_2_Value)) :-
write(Obj_2_Value), nl.
% not object 2 - still return true, but don't do anything
dosomething(_).
?- maplist(dosomething, [obj1(brown), obj2(hello), obj3(fred), obj2(stack), obj4(bun), obj2(overflow)]).
hello
stack
overflow
true .