有疑問時,嘗試發出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