How do I remove surrounding parentheses in a nested list in Scheme if that nested list has 1 element?
-
10-02-2021 - |
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!
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:
- Checks if the list is empty
- Checks if the first item is a list, if not
cons
it to the function applied tocdr
of the list - Otherwise, applies the function to both
car
andcdr
andcons
ing 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.