我是Prolog的新手,所以我在某项任务中遇到了一些问题.任务是编写尾递归谓词count_elems(List,N,Count)
条件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)
我不太清楚问题出在哪里.thx任何帮助:)
如果你想编写一个尾递归版本的代码,你需要(如CapelliC指出的那样)一个额外的参数来充当累加器.您可以在第一个子句中看到问题:
count_elems(L, N, Count) :- count_elems(L,N,0).
这里Count
是一个单例变量,没有在任何地方实例化.您对start count_elems
开始的递归调用计数0
,但不再需要使用total实例化变量.所以,你需要:
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
您还可以使用"if-else"结构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源文件.