Flatten List

Function Syntax (LM:flatten <l>)
Current Version 1.0
Donate
Arguments
Symbol Type Description
l List List to process
Returns
Type Description
List The supplied list with all nested structures removed

Function Description

This function will transform a nested list (i.e. a list containing other lists), into a non-nested (simple) list by removing all nested structure from the list (flattening it), whilst retaining all list elements.

The following version will treat nil as an atom, and hence not remove it from the list.

Select all
;; Flatten List  -  Lee Mac
;; Transforms a nested list into a non-nested list

(defun LM:flatten ( l )
    (if (atom l)
        (list l)
        (append (LM:flatten (car l)) (if (cdr l) (LM:flatten (cdr l))))
    )
)

Example Function Call

_$ (LM:flatten '(0 (1 (2 . 3) (4 (5 (6 7) (8 (9)) 0)))))
(0 1 2 3 4 5 6 7 8 9 0)

Variation to Remove nil Values

The following version of the function will consider nil as an empty list and remove it from the result.

Select all
;; Flatten List  -  Lee Mac
;; Transforms a nested list into a non-nested list with null values removed

(defun LM:flatten-nils ( l )
    (if l
        (if (atom l)
            (list l)
            (append (LM:flatten-nils (car l)) (LM:flatten-nils (cdr l)))
        )
    )
)

Example Function Call

_$ (LM:flatten-nils '(0 (1 (2 . 3) ( ) (4 (5 (6 nil 7) (8 (9)) 0)))))
(0 1 2 3 4 5 6 7 8 9 0)

textsize

increase · reset · decrease

Designed & Created by Lee Mac © 2010