Brackets for brackets?

I want to write code using a recursive function to turn off parentheses in LIST.

Here's an example:

(unnest '(1 (2 (3)) (4 5))) ==> (1 2 3 4 5)

      

+2


source to share


1 answer


(defun unnest (lst)
  (cond ((null? lst) '())
        ((not (list? lst)) (list lst))
        (t
         (append (unnest (car lst))
                 (unnest (cdr lst))))))

> (unnest '(1 (2 (3)) (4 5))) 
(1 2 3 4 5)

      

Basically the idea is this:



  • if you have an empty list , then you obviously don't need to bother it;
  • if it is not a list , then it must be an atom, and therefore you return a list containing that atom;
  • in the last condition, you have a list , so you basically say: the result of the unnamed list is the unnamed version of the first item added to the unnamed version of the rest of the list, and that it, recursion, takes care of the rest.

Hope it helps.

+5


source







All Articles