Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Im trying to get the following
?- count_nested([a,[1,2,[3]],[4,[5,[5],6]]],El).
El = 8
With the following code
count_nested([],0).
count_nested([_|T],El):-
count_nested(T,N),
El is N + 1.But I get the following
?- count_nested([a,[1,2,[3]],[4,[5,[5],6]]],El).
El = 3
Whats going on I just can't get ti to go throught the nested list?

hello,
your code is counting thenumber of elements in the (most-outter) list. but i don't get what count_nested is supposed to do. if it should count the number of nested lists, then why it should return 8?
if count_nest is supposed to counts all elements of the list which contains sublists as well, then you can just "flatten" the list by the (swi-prolog) builtin predicate "flatten".
hope that then
wtk =)

This code works too:
cnt_nested([], 0).
cnt_nested([H|T], N) :- list(H), !, cnt_nested(H, HN), cnt_nested(T, TN), N is HN + TN + 1.
cnt_nested([_|T], N) :- cnt_nested(T, N).with the query you provided -
cnt_nested([a,[1,2,[3]],[4,[5,[5],6]]],El).El -> 5.
As WTK pointed out, why do u think it should return 8??
This code is independant of which Prolog u use too!

Appologies, list/1 is GNU prolog built-in.
If your prolog doesn't have same (or similar) then uselist([]).
list([_|T]) :- list(T).

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |