0

I am having trouble writing a Scheme procedure that takes a tree (represented as a list) and returns a list whose elements are all the leaves of the tree arranged in right to left order.

For example, if I were to call: ( leaves '(((1 2) (3 4)) ((1 2) (3 4))) ) I would get: '(4 3 2 1 4 3 2 1)

I have the following so far, and the output is technically correct, but there is an issue with the parenthesis:

(define (leaves givenList)
  (if (null? givenList) givenList
      (if (list? (car givenList))
          (append (leaves (cdr givenList)) (cons (leaves (car givenList)) '()))
          (append (leaves (cdr givenList)) (list (car givenList))))))

The output when I call: ( leaves '(((1 2) (3 4)) ((1 2) (3 4))) ) is: (((4 3) (2 1)) ((4 3) (2 1)))

I need to get rid of the parenthesis on the inside and just get: '(4 3 2 1 4 3 2 1)

Any help or insight is greatly appreciated. Thanks!

ad absurdum
  • 19,498
  • 5
  • 37
  • 60
  • 2
    Break this into two problems: 1. flatten nested lists into a single list, 2. reverse a list. – Barmar Sep 17 '21 at 20:19
  • 1
    since both tails have `append` or return `()` you know the result is a proper list. What is the purpose of `cons`-ing the result before appening? – Sylwester Sep 17 '21 at 22:44
  • 1
    Refer to [Writing flatten method in Scheme](https://stackoverflow.com/questions/8387583/writing-flatten-method-in-scheme). Once you have `flatten`, you can define `leaves` as `(define (leaves given-list) (reverse (flatten given-list)))`. – Flux Sep 18 '21 at 03:13

0 Answers0