views:

271

answers:

1

I want to write code (using recursive function) to unnest the parentheses in a LIST in Lisp language. Example:

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

Thanks. Any help is appreciated!

+4  A: 
(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 as follows:

  • if you have an empty list, then you obviously don't need to unnest it;
  • if it's 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 an unnested list is the unnested version of the first element appended to the unnested version of the rest of the list, and that's it, recursion takes care of the rest.

Hope it helps.

JG
or more simply, we are walking a tree and we pick the leaf nodes, which we append to a list recursively. The *trick* to avoid reconstructing again a tree structure is to use the `append` function.
Nick D
Yes, that is more simple : P. Btw, why did you replace the `t` for `else`? `else` is used in Scheme.
JG
Yes, I experiment with Scheme and I thought `t` was a mistake :o) Rollback my edit if you want. BTW, what's `t`?
Nick D
Sure, no problem. `t` is LISP's `t`rue value; a cheap way not to have a special `else` case in `cond` : ).
JG