Elisp: Proper List
What is Proper List
A cons structure whose last tail is nil, is called Proper List, or nil-terminated list.
;; proper lists (cons nil nil) (cons 3 nil) (cons 3 (cons 3 nil)) (cons 3 (cons 3 (cons 3 nil))) (cons 3 (cons 3 (cons 3 (cons 3 nil)))) ;; also proper lists. right-most tail is nil (cons (cons 3 4) nil) (cons (cons 3 4) (cons 3 nil)) (cons (cons (cons 3 4) 4) nil) ;; also proper list nil
Test If a List is a Proper List
proper-list-p
-
Return length if it is a proper list, else nil.
(proper-list-p nil) ;; true (proper-list-p (cons nil nil)) (proper-list-p (cons 3 nil)) (proper-list-p (cons 3 (cons 3 nil))) (proper-list-p (cons 3 (cons 3 (cons 3 nil)))) (proper-list-p (cons 3 (cons 3 (cons 3 (cons 3 nil))))) ;; all true (proper-list-p (cons (cons 3 4) nil)) ;; true
Improper List
A cons that's not proper list is called Improper List .
;; improper list (cons nil 3) (cons (cons 3 nil) 3)
;; improper list ;; all false ;; tail is not nil (proper-list-p (cons nil 3)) ;; tail is not nil (proper-list-p (cons (cons 3 nil) 3))
Proper List vs Improper List
- Any cons structure, is a list.
- Proper list and improper list are both lists.
Most list functions, assume you have a proper list. That is, they assume you have a nil as the last tail in the cons structure. Practically all functions that return a list, return a proper list. This is critical to know.
Improper list is basically never used except a single non-nested cons pair holding 2 values.