有疑问时,尝试发出trace/0
调用(或等值的实现)运行您的谓词之前。你会在这里看到你的递归不完全正确。
这是一个正确的递归(@user1126943)的外观时,执行这样的:
[trace] ?- foundValues([1, 2], [1, 2, 3], R).
Call: (6) foundValues([1, 2], [1, 2, 3], _G383) ? creep
Call: (7) lists:member(1, [1, 2, 3]) ? creep
Exit: (7) lists:member(1, [1, 2, 3]) ? creep
Call: (7) foundValues([2], [1, 2, 3], _G465) ? creep
Call: (8) lists:member(2, [1, 2, 3]) ? creep
Exit: (8) lists:member(2, [1, 2, 3]) ? creep
Call: (8) foundValues([], [1, 2, 3], _G468) ? creep
Exit: (8) foundValues([], [1, 2, 3], []) ? creep
Exit: (7) foundValues([2], [1, 2, 3], [2]) ? creep
Exit: (6) foundValues([1, 2], [1, 2, 3], [1, 2]) ? creep
R = [1, 2].
基本上列表向后建,你可以看到。首先我们到达基本案例([]
),然后根据我们如何到达这种情况(意思取决于元素是否是第二个列表的成员或不在此处)添加元素。
使用SWI-Prolog,你也可以使用内建的谓词相交/ 3。 – gusbro 2012-01-04 13:34:16