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
).
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.
Thank you!
Your code is incorrect for the
is_list(H)
branch: in that case you ignore the value ofN1
, which is not correct, you wantN
to be the sum ofN1
with the count onH
.Complete code: