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!
Remove items from a Nested List. If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item. If you don't need the removed value, use the del statement.
A nested list is simply a list that occurs as an element of another list (which may of course itself be an element of another list, etc.). Common reasons nested lists arise are: They're matrices (a list of rows, where each row is itself a list, or a list of columns where each column is itself a list).
Lists can be nested within other lists, as shown in the following example that details a sequenced plan to relocate. In this case, it's an ordered list inside another one, though you can nest any type of list within any other type (see the dl entry in this chapter for a related note).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With