Prolog 计数列表元素高于 n [英] Prolog count list elements higher than n
问题描述
我对 Prolog 有点陌生,所以我在执行某项任务时遇到了一些问题.任务是写一个尾递归谓词count_elems(List,N,Count)
condition List_Element >N,Count1为Count+1
.
I'm kinda new to Prolog so I have a few problems with a certain task. The task is to write a tail recursive predicate count_elems(List,N,Count)
condition List_Element > N, Count1 is Count+1
.
我的方法:
count_elems( L, N, Count ) :-
count_elems(L,N,0).
count_elems( [H|T], N, Count ) :-
H > N ,
Count1 is Count+1 ,
count_elems(T,N,Count1).
count_elems( [H|T], N, Count ) :-
count_elems(T,N,Count).
错误消息:
ERROR: toplevel: Undefined procedure: count_elems/3 (DWIM could not correct goal)
我不太确定问题出在哪里.感谢任何帮助:)
I'm not quite sure where the problem is. thx for any help :)
推荐答案
如果您想制作代码的尾递归版本,您需要(正如 CapelliC 指出的那样)一个额外的参数来充当累加器.您可以在第一个子句中看到问题:
If you want to make a tail-recursive version of your code, you need (as CapelliC points out) an extra parameter to act as an accumulator. You can see the issue in your first clause:
count_elems(L, N, Count) :- count_elems(L,N,0).
这里,Count
是一个单例变量,没有在任何地方实例化.您对 count_elems
的递归调用从 0
开始计数,但不再有要使用总数实例化的变量.所以,你需要:
Here, Count
is a singleton variable, not instantiated anywhere. Your recursive call to count_elems
starts count at 0
, but there's no longer a variable to be instantiated with the total. So, you need:
count_elems(L, N, Count) :-
count_elems(L, N, 0, Count).
然后声明 count_elem/4
子句:
count_elems([H|T], N, Acc, Count) :-
H > N, % count this element if it's > N
Acc1 is Acc + 1, % increment the accumulator
count_elems(T, N, Acc1, Count). % check the rest of the list
count_elems([H|T], N, Acc, Count) :-
H =< N, % don't count this element if it's <= N
count_elems(T, N, Acc, Count). % check rest of list (w/out incrementing acc)
count_elems([], _, Count, Count). % At the end, instantiate total with accumulator
您还可以对 count_elems/4
使用if-else"结构:
You can also use an "if-else" structure for count_elems/4
:
count_elems([H|T], N, Acc, Count) :-
(H > N
-> Acc1 is Acc + 1
; Acc1 = Acc
),
count_elems(T, N, Acc1, Count).
count_elems([], _, Count, Count).
此外,正如 CapelliC 指出的那样,您陈述的错误消息可能是由于没有读取您的 prolog 源文件.
Also as CapelliC pointed out, your stated error message is probably due to not reading in your prolog source file.
这篇关于Prolog 计数列表元素高于 n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!