Last Updated: February 25, 2016
· euantor

Flatten a multi-dimensional list in Lisp

I recently hit a wall in my AI Programming course (in which we use Lisp) when working with multi-dimensional lists and trying to find the minimum and maximum values. Lisp seemingly doesn't have any kind of built in flatten function to take a multi-dimensional list and return a single dimensional one. After a bit of head scratching though, we reached the following simple flatten function:

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

You use the function like so:

(flatten '(1 3 5 7 (9 3 4) (2)))

This would return:

(1 3 5 7 9 3 4 2)