【发布时间】:2017-12-05 21:31:47
【问题描述】:
- 我想为每个元素比较 2 个列表。
- 计算相等元素的数量。
我很近,请帮帮我:
%list vs list%
count2([],[],0).
count2([H1|T1],[H2|T2],S):-
count(H1,[H2|T2],N),
count2(T1,[H2|T2],M),
S is N+M.
%1 element vs 1 list%
count(_, [], 0).
count(X, [X | T], N) :-
!, count(X, T, N1),
N is N1 + 1.
count(X, [_ | T], N) :-
count(X, T, N).
A test:
1 ?- count2([2],[1,2,3],S).
false.
追踪:
2 ?- count2([2],[1,2,3],S).
Redo: (5) read_history(h, '!h', [trace, end_of_file], '~! ?- ', _G154, _G155) ? creep
Correct to: "count2([2],[1,2,3],S)"?
Please answer 'y' or 'n'? yes
Call: (7) count2([2], [1, 2, 3], _G306) ? creep
Call: (8) count(2, [1, 2, 3], _G631) ? creep
Call: (9) count(2, [2, 3], _G631) ? creep
Call: (10) count(2, [3], _G631) ? creep
Call: (11) count(2, [], _G631) ? creep
Exit: (11) count(2, [], 0) ? creep
Exit: (10) count(2, [3], 0) ? creep
Call: (10) _G632 is 0+1 ? creep
Exit: (10) 1 is 0+1 ? creep
Exit: (9) count(2, [2, 3], 1) ? creep
Exit: (8) count(2, [1, 2, 3], 1) ? creep
Call: (8) count2([], [1, 2, 3], _G637) ? creep
Fail: (8) count2([], [1, 2, 3], _G637) ? creep
Redo: (11) count(2, [], _G631) ? creep
Fail: (11) count(2, [], _G631) ? creep
Fail: (10) count(2, [3], _G631) ? creep
Fail: (9) count(2, [2, 3], _G631) ? creep
Fail: (8) count(2, [1, 2, 3], _G631) ? creep
Fail: (7) count2([2], [1, 2, 3], _G306) ? creep
false.
(返回解决方案,但递归有问题)
请求的输出 #1:
?- count2([2],[1,2,3],S).
S = 1.
(2 是列表中的 1 次)。
请求的输出 #2:
?- count2([1,2],[1,2,3],S).
S = 2
(1 是列表中的 1 次)。 (2 是列表中的 1 次)。 总计 = 2 个相等的元素。
【问题讨论】:
-
什么不起作用?请提供一个示例查询,其中包含您获得的输出和请求的输出...
-
好的编辑,等一下
-
关于列表的假设是什么?查询
count2([1,2], [3,2,1], S).会产生什么结果? -
(1 是列表中的 1 次)。 (2 是列表中的 1 次)。总计 = 2 个相等的元素。
标签: list recursion count prolog