Reputation: 3761
How can I count nested list elements in Prolog? I have the following predicates defined, which will count a nested list as one element:
length([ ], 0).
length([H|T],N) :- length(T,M), N is M+1.
Usage:
?- length([a,b,c],Out).
Out = 3
This works, but I would like to count nested elements as well i.e.
length([a,b,[c,d,e],f],Output).
?- length([a,b,[c,d,e],f],Output).
Output = 6
Upvotes: 4
Views: 5192
Reputation: 2173
len([H|T],N) :-
len(H, LH),
len(T, LT),
!,
N is LH + LT.
len([], 0):-!.
len(_, 1):-!.
Test:
?- len([a,b,[c,d,e],f],Output).
Output = 6.
Upvotes: 3