在列表中计算事件 [英] Counting occurrences in list
问题描述
我试图创建一个规则来计算给定列表中某个元素的出现次数,我到目前为止所尝试的方式似乎并不符合我的预期:
第一个参数应该是列表,第二个是我们正在寻找的元素,最后一个是出现次数:
%空列表应始终返回0次出现
count([],E,0): - true。
%如果我们的头是我们正在寻找的,计数
count([E | T],E,N): - count(T,E,N-1)。
%否则,不计数
count([H | T],E,N): - H \ == E,count(T,E,N)。
这里 H
和 T
<例如
count([],1,N)
按预期返回 N = 0
非空,我们总是得到 false。
: ? - count [1],1,N)。
false。
? - count([1,2,1,3],1,N)。
false。
任何人都可以指出我做错了什么?
更新:
用
替换第二行似乎有效 count([E | T],E,N + 1): - count(T,E,N)。
但我不知道为什么这不等同于我的第一个想法。
然后我们得到
? - count([1,2,1,3] ,1,N)。
N = 0 + 1 + 1
这是正确的。
问题是 N + 1
(或 N-1
%空列表有0次出现
在
count([],_,0)。
%如果我们的头是我们正在寻找的,计数
count([E | T],E,N): -
N_1是N - 1,%this是重要的一个
计数(T,E,N_1)。
%否则不计数
count([H | T],E,N): -
H \ == E,
count ,E,N)。
N-1
的下一次调用中, >。这就是为什么在第二个例子中,你最终得到N = 0 + 1 + 1
而不是N = 2
。I'm trying to create a rule that counts the number of occurrences of a certain element in a given list, what I've tried so far does not seem to work the way I expect:
The first argument here should be the list, the second one the element we are looking for, and the last one the number of occurrences:
%empty list should always return 0 occurences count([],E,0) :- true. %if our head is what we are looking for, count count([E|T],E,N) :- count(T,E,N-1). %otherwise, do not count count([H|T],E,N) :- H \== E, count(T,E,N).
Here
H
is the head andT
the tail of the given list.The base case e.g.
count([],1,N).
returnsN = 0
as expected, but as soon as the list is non empty, we always getfalse.
:?- count([1],1,N). false. ?- count([1,2,1,3],1,N). false.
Can anyone point out what I'm doing wrong?
Update:
It seems to work when replacing the second line with
count([E|T],E,N+1) :- count(T,E,N).
But I just cannot figure out why this is not equivalent to my first idea.
Then we get
?- count([1,2,1,3],1,N). N = 0+1+1
which is correct.
解决方案The problem is that
N+1
(orN-1
) isn't evaluated, as can be seen by your second (working) example.% empty list has 0 occurrences count([], _, 0). % if our head is what we are looking for, count count([E|T], E, N) :- N_1 is N - 1, % this is the important one count(T, E, N_1). % otherwise, do not count count([H|T], E, N) :- H \== E, count(T, E, N).
is
actually evaluates the equation, instead of unifying theN
in your next call withN-1
. That's why in your second example, you end up withN=0+1+1
instead ofN=2
.这篇关于在列表中计算事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!