Prolog递归计数列表中的数字 [英] Prolog recursively count numbers in a list
问题描述
我需要一个程序来计算列表中的所有数字,无论它们的嵌套程度如何.如果它们不在另一个列表中,但能够通过深度嵌套的元素递归无法解决,我能够对它们进行计数.到目前为止,我已经知道了:
I need a program to count all the numbers in a list, no matter how DEEPLY NESTED they are. I was able to count numbers in the case where they were not inside another list, but recursing through deeply nested elements is not working out. I have this so far:
count([],0).
count([H|Tail], N) :-
count(Tail, N1),
( number(H)
->N is N1 + 1
; is_list(H)
-> count(H,N)
; N = N1
).
因此,如果我要调用count([a,1,[2,b],3],N)
,则输出应为N=3
;但是,我只得到N=2
.有人可以帮我添加第二个案例测试吗?这里所有可用的解决方案都不适用于深度嵌套的数字元素.
So, if I were to call count([a,1,[2,b],3],N)
, the output should be N=3
; however, I only get N=2
. Could someone please help me add to my second case test? All available solutions here do not work for deeply nested numerical elements.
谢谢!
推荐答案
对于is_list(H)
分支,您的代码不正确:在这种情况下,您忽略了N1
的值,这是不正确的,您需要N
是N1
与H
上的计数之和.
Your code is incorrect for the is_list(H)
branch: in that case you ignore the value of N1
, which is not correct, you want N
to be the sum of N1
with the count on H
.
完整代码:
:- use_module(library(clpfd)).
count([], 0).
count([H|T], N) :-
count(T, N1),
( number(H) ->
N #= N1 + 1
; is_list(H) ->
N #= N1 + N2,
count(H, N2)
; N1 = N
).
这篇关于Prolog递归计数列表中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!