Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove surrounding parentheses in a nested list in Scheme if that nested list has 1 element?

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!

like image 370
hal88 Avatar asked Oct 15 '11 08:10

hal88


People also ask

How do I remove items from my nested list?

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.

What is nested Listt?

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).

Can a list be nested in another 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).


1 Answers

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)
like image 60
Óscar López Avatar answered Nov 15 '22 09:11

Óscar López