Finding deepest sublist

Discussion of Common Lisp
Post Reply
malko93
Posts: 2
Joined: Sun Feb 06, 2011 5:31 pm

Finding deepest sublist

Post by malko93 » Sun Feb 06, 2011 5:42 pm

Hi, I must say that LISP is a new programming language to me and quite difficult one. Unfortunately I'm stuck right at the start, while trying to solve some exercises, so I'm thinking perhaps you could give me some pointers. The problem sounds simple - as I've already mentioned in the title, I want to find the deepest sublist (for example, the 1st element there) in the received list. I'm struggling with determining the right technique, hope you could help with some directions.

gugamilare
Posts: 406
Joined: Sat Mar 07, 2009 6:17 pm
Location: Brazil
Contact:

Re: Finding deepest sublist

Post by gugamilare » Tue Feb 08, 2011 5:29 am

I think the simpler way to do this is using two functions.

One, called "depth-of-list", will determine the depth of a list.
The other, called "find-deepest-sublist", will determine which sublist is the deepest one.

What is the definition of depth of a list? That is simple: the empty list (i.e., NIL) have depth 0. For a non-empty list, it is the depth of the deepest sublist plus one.
Therefore, the function "depth-of-list" will check if the list is NIL. If it is, return zero. Otherwise, it calls "find-deepest-sublist" and recursively calls "depth-of-list" in that list.

The function "find-deepest-sublist" now is easy to do. It has to iterate over all elements of a list (using dolist or loop), calculate the depth of that element (using "depth-of-list") and return whichever elements have the highest depth.

Good luck! In case you are stuck with the concepts of Common Lisp, try Practical Common Lisp.

malko93
Posts: 2
Joined: Sun Feb 06, 2011 5:31 pm

Re: Finding deepest sublist

Post by malko93 » Wed Feb 09, 2011 4:11 pm

Thanks for the reply, however I've already solved the problem in another way. I wrote a function that flattens a list by 1 level - based on this, I was able to determine the deepest sublist (until list flattening returns an empty list) and print the 1st element out. Anyway, thanks for the help, will try to do it like you suggested.

Post Reply