Question

Say I have the list: (a b ((c)) (d + e) ((e + f)) (g) () h)

How do I get the following list (preferably with a function):(a b c (d + e) (e + f) g h)

In other words:

  • If the nested list has only one element it is simplified to the element. That is ((c)) is simplified to just c in the above example. Also ((e + f)) becomes (e + f).

  • If the nested list has more than one element then it remains the same. That is (d + e) remains as (d + e) in the above example.

  • If the nested list is null, it is simply removed.

Lastly I'm not sure if the term flatten applies in this case. I hope my question is clear. If not, please let me know.

Thanks in advance!

Was it helpful?

Solution

Try with this code:

(define (atom? x)
  (and (not (pair? x)) (not (null? x))))

(define (strip lst)
  (if (or (null? lst) (atom? lst) (not (null? (cdr lst))))
      lst
      (strip (car lst))))

(define (flatten lst)
  (cond ((or (null? lst) (atom? lst))
         lst)
        ((null? (strip (car lst)))
         (flatten (cdr lst)))
        (else
         (cons (flatten (strip (car lst))) (flatten (cdr lst))))))

When tested with your example, it gives the expected answer:

> (flatten '(a b ((c)) (d + e) ((e + f)) (g) () h))
> (a b c (d + e) (e + f) g h)

OTHER TIPS

The idea is that you need a recursive function that:

  1. Checks if the list is empty
  2. Checks if the first item is a list, if not cons it to the function applied to cdr of the list
  3. Otherwise, applies the function to both car and cdr and consing the results.

Here's an untested attempt:

(define flatten
  (lambda lst
    (cond 
      ((null? lst) lst)
      ((atom? (car lst)) (cons (car lst) (flatten (cdr lst))))
      (else (cons (flatten (cons (car (car lst) (cdr (car ls))) 
                  (flatten (cdr lst)))))))

Where atom? is a function that tests if an element in a list not a list. Here is how atom? is defined in The Little Schemer:

(define atom?
  (lambda (x)
    (and (not (pair? x)) (not (null? x)))))

I highly recommend The Little Schemer if you are having trouble organizing the logic of recursive functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top