问题
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!
回答1:
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
.
Complete code:
:- 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
).
来源:https://stackoverflow.com/questions/47259887/prolog-recursively-count-numbers-in-a-list