How to remove nested parentheses in LISP

Solution 1:

Here's what I'd do:

(ql:quickload "alexandria")
(alexandria:flatten list)

That works mainly because I have Quicklisp installed already.

Solution 2:

(defun flatten (l)
  (cond ((null l) nil)
        ((atom l) (list l))
        (t (loop for a in l appending (flatten a)))))

Solution 3:

I realize this is an old thread, but it is one of the first that comes up when I google lisp flatten. The solution I discovered is similar to those discussed above, but the formatting is slightly different. I will explain it as if you are new to lisp, as I was when I first googled this question, so it's likely that others will be too.

(defun flatten (L)
"Converts a list to single level."
    (if (null L)
        nil
        (if (atom (first L))
            (cons (first L) (flatten (rest L)))
            (append (flatten (first L)) (flatten (rest L))))))

For those new to lisp, this is a brief summary.

The following line declares a function called flatten with argument L.

(defun flatten (L)

The line below checks for an empty list.

    (if (null L)

The next line returns nil because cons ATOM nil declares a list with one entry (ATOM). This is the base case of the recursion and lets the function know when to stop. The line after this checks to see if the first item in the list is an atom instead of another list.

        (if (atom (first L))

Then, if it is, it uses recursion to create a flattened list of this atom combined with the rest of the flattened list that the function will generate. cons combines an atom with another list.

            (cons (first L) (flatten (rest L)))

If it's not an atom, then we have to flatten on it, because it is another list that may have further lists inside of it.

            (append (flatten (first L)) (flatten (rest L))))))

The append function will append the first list to the start of the second list. Also note that every time you use a function in lisp, you have to surround it with parenthesis. This confused me at first.

Solution 4:

You could define it like this for example:

(defun unnest (x)
  (labels ((rec (x acc)
    (cond ((null x) acc)
      ((atom x) (cons x acc))
      (t (rec (car x) (rec (cdr x) acc))))))
    (rec x nil)))

Solution 5:

(defun flatten (l)
  (cond ((null l) nil)
        ((atom (car l)) (cons (car l) (flatten (cdr l))))
        (t (append (flatten (car l)) (flatten (cdr l))))))