4
votes

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

1
Hi Shaggy, I am using prolog in my course, however this isn't a direct homework question. I plan to implement something like this in a future project though.Blair

1 Answers

3
votes
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.