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的值code>,这是不正确的,您希望
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屋!