Computing.Net > Forums > Programming > Nested Lists in Prolog Help Needed

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Nested Lists in Prolog Help Needed

Reply to Message Icon

Name: Stewart
Date: November 13, 2003 at 16:37:59 Pacific
OS: Win XP
CPU/Ram: 2800
Comment:

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?



Sponsored Link
Ads by Google

Response Number 1
Name: wtk
Date: November 13, 2003 at 23:29:14 Pacific
Reply:

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 =)


0

Response Number 2
Name: Gagey
Date: November 17, 2003 at 18:27:13 Pacific
Reply:

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!


0

Response Number 3
Name: Gagey
Date: November 17, 2003 at 18:34:01 Pacific
Reply:

Appologies, list/1 is GNU prolog built-in.
If your prolog doesn't have same (or similar) then use

list([]).
list([_|T]) :- list(T).


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

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


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: Nested Lists in Prolog Help Needed

Prolog | Lists | anbody help www.computing.net/answers/programming/prolog-lists-anbody-help/14336.html

file sizes in java help needed? www.computing.net/answers/programming/file-sizes-in-java-help-needed/10094.html

prob with Linked list in C www.computing.net/answers/programming/prob-with-linked-list-in-c/481.html