1

I asked several days ago about finding the most deeply nested lists. I implemented the idea that was given, and it works.

But there is another problem: I also need to build a list from the nested list. meaning: If I change (8) and (10 11 12), to leaf1 and leaf2, I need to return: '(ans (leaf1 (8)) (leaf2 (10 11 12)). /ans is a quote

In other words: my function will get (1 (2 3) (4 (5) (7 (8) (10 11 12)))))) => the most nested lists are (8) and (10 11 12) => my function will return '(ans (leaf1 (8)) (leaf2 (10 11 12)).

I am trying to find an idea, not an implementation. Thanks.

Community
  • 1
  • 1
Adam Sh
  • 8,137
  • 22
  • 60
  • 75

1 Answers1

1

Yes, this is easy to do. Currently (if I understand correctly) you have a recursive function that descends a tree and uses cons to build a modified copy (in which the most deeply-nested lists are replaced with something). This is a common pattern for tree-recursive functions, but there's no reason they have to return a value with a similar structure to the input they recur on. For example, you could write a function to walk a tree of numbers and return their sum.

In this case it sounds like you probably want to keep the basic structure of your tree-recursive function, but use cons or possibly append to build a flat list of the most-deeply-nested-lists you've found.

I can't quite tell from your question, but you might also be looking for a way to write a function that returns two separate values: one being the tree with deeply-nested-lists replaced by something else, and the other being the flat list of the replaced bits themselves. In this case you might want to look into the Scheme procedures values and call-with-values, and maybe the library form let-values if your Scheme has it. See the Schemewiki FAQ here for more info (scroll down).

  • Sorry, but I didn't understand. I build procedure thar replace the most nested value in a list. But the big problem, that this is a recursive method, so I cant build a new list from this method, and only change it. I didn't understand the use of call-with-values in this question. Thanks for your help. – Adam Sh Dec 10 '11 at 09:22
  • 1
    @AdamSh: you certainly can build a new list in a recursive function: that's how most of the standard functions like `map` and `filter` work. It's hard to give better advice without seeing your code, but here are two toy problems which might be helpful: (1) write a function to take a tree of integers and return a similar tree with each number doubled (*without* modifying the original tree); (2) modify this function to add up all the numbers instead, or make a flat list of them. If you have trouble with this, I'd suggest getting a copy of _The Little Schemer_ and working through it. Good luck! –  Dec 11 '11 at 07:54