[英]Having trouble with predicate in Prolog
I am trying to right a predicate in Prolog that accepts an item, a list, and a number, and checks to see if the item is in the list that number of times. 我试图在Prolog中纠正一个谓词,该谓词接受一个项目,一个列表和一个数字,并检查该项目是否在列表中达到该次数。 For example
例如
count(7,[3,7],X).
would return X=1
. 将返回
X=1
。
count(7,[3,7],1).
would return true
会返回
true
This is what I have so far 这就是我到目前为止
count_occur(A,[0|B],D).
count_occur(A,[A|C],D) :- count_occur(A,C,D1), D is D1+1.
count_occur(A,[B|C],D) :- count_occur(A,C,D).
I am very new to Prolog and really struggling to understand this programming paradigm. 我对Prolog并不陌生,并且真的很难理解这种编程范例。
What I am trying to do is to see if the first item in the list matches the passed-in value (A), if it does increment D and check again against the remainder of the list. 我想做的是查看列表中的第一项是否与传入的值(A)相匹配,如果它确实使D递增,然后再次对照列表的其余部分进行检查。 This is how I would do it in lisp or another language anyway.
无论如何,这就是我要用轻快的语言或其他语言做到的方式。 Could really use some help, been at this for a while and it just isn't clicking for me.
真的可以使用一些帮助,已经有一段时间了,但这并不是我想要的。
I don't have prolog right now to test it, but I would try it like that: 我目前没有prolog可以对其进行测试,但是我会这样尝试:
count_occur(A, [], 0).
count_occur(A, [A|T], D):- count_occur(A, T, D1), D is D1 + 1.
count_occur(A, [B|T], D):- A \= B, count_occur(A, T, D).
The idea is that if the list is empty, there is 0 occurrences of each element. 这个想法是,如果列表为空,则每个元素出现0次。 The rest is almost the same as yours as I think that it is correct.
其余的与您的几乎一样,因为我认为这是正确的。
The only difference is that I have added A \\= B
, which should mean A \\neq B
. 唯一的区别是我添加了
A \\= B
,这应该表示A \\neq B
I think that otherwise it will accept A == B
, which might lead to count_occur(3, [3], 0).
我认为否则它将接受
A == B
,这可能会导致count_occur(3, [3], 0).
being true. 是真的。 You should check about that.
您应该检查一下。
I hope this helps! 我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.