Prolog 计算列表中的元素
我想计算列表中出现了多少个 g 项目,下面是我现在正在尝试的代码,但返回时得到错误。
g(E) :- memberchk(E, [apple, orange, pear, grape, lycee, pineapple,dragonfruit]).
countFruit([], No):- write(' >> No of Fruits : '), write(No), nl.
countFruit([H|T], No) :- not(g(H)), countFruit(T,No).
countFruit([H|T], No) :- No1 is No+1, countFruit(T,No1).
?countFruit(H,0). (H is a list).
I want to count how many g items appear in a list, below is the code I was trying now, but I got false when return.
g(E) :- memberchk(E, [apple, orange, pear, grape, lycee, pineapple,dragonfruit]).
countFruit([], No):- write(' >> No of Fruits : '), write(No), nl.
countFruit([H|T], No) :- not(g(H)), countFruit(T,No).
countFruit([H|T], No) :- No1 is No+1, countFruit(T,No1).
?countFruit(H,0). (H is a list).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过调用
?- countFruit(H,0).
您告诉 prolog 将countfruit\2
谓词中的No
变量统一为0
。因此结果只能是0
或fail
。如果我按原样运行您的代码,我会得到以下信息:
这是我对此问题的看法:
By calling
?- countFruit(H,0).
you are telling prolog to unify theNo
variable in yourcountfruit\2
predicate to0
. So the result can only ever be0
orfail
.If I run your code as-is though, I get the following:
Here's my take on this problem:
您的代码包含一个错误:由于 countFruit/2 的第二个和第三个子句使用相同的头,因此您应该在第二个子句中的 not(g(H)) 测试之后添加一个剪切。否则,你会在回溯时得到错误的答案。
此外,您可以通过检查 g(H) 并相应地重新表述第二个和第三个子句来简化代码,而不是使用 not(g(H))。但这只是美化而已。
除此之外,我看不出您的代码有明显的问题。您能提供导致“错误”的实际查询吗?
Your code contains one bug: since the second and third clause of countFruit/2 use the same head, you should add a cut after the not(g(H)) test in the second clause. Otherwise, you'll get a wrong answer on backtracking.
Also, instead of using not(g(H)), you could simplify the code by checking for g(H) instead and reformulating the second and third clause accordingly. But that's just beautifying.
Other than that, I can't see an obvious problem with your code. Can you supply the actual query that resulted in 'false'?.