How to remove surrounding parentheses in a nested list in a Scheme if this nested list has 1 element?

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

How to get the following list (preferably with a function): (abc (d + e) (e + f) gh)

In other words:

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

  • If the nested list contains more than one item, it remains the same. That is, (d + e) remains in (d + e) in the above example.

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

Finally, I'm not sure if the term flatten is used in this case. Hope my question is clear. If not, let me know.

Thanks in advance!

+6
source share
2 answers

Try using 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 testing with your example, it gives the expected answer:

 > (flatten '(ab ((c)) (d + e) ((e + f)) (g) () h)) > (abc (d + e) (e + f) gh) 
+5
source

The idea is that you need a recursive function that:

  • Checks if empty
  • Checks if the first element is a list, if not cons its function, applied to the cdr list
  • Otherwise, the function is applied for both car and cdr and cons results.

Here's an unverified 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 is the atom? is a function that checks if an item is in a list, not a list. Here's how an atom? 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.

0
source

Source: https://habr.com/ru/post/899355/


All Articles