Lisp Length Functions
Sunday, July 23rd, 2006SIMPLE-LENGTH returns the number of items in the top level of a list.
Examples:
- (SIMPLE-LENGTH ‘(a b c)) returns 3
- (SIMPLE-LENGTH ‘(a (b c))) returns 2
- (SIMPLE-LENGTH ‘(a b c (a (b c)))) returns 4
(defun SIMPLE-LENGTH (lst)
(cond
((null lst) 0)
(t (+ 1 (SIMPLE-LENGTH (cdr lst))))
)
)
COMPLEX-LENGTH returns the numbers of atoms in a list no matter how deeply nested they are.
Examples:
- (COMPLEX-LENGTH ‘(a b c)) returns 3
- (COMPLEX-LENGTH ‘(a (b c))) returns 3
- (COMPLEX-LENGTH ‘(a b c (a (b c)))) returns 6
(defun COMPLEX-LENGTH (lst)
(cond
((null lst) 0)
((atom (car lst)) (+ 1 (COMPLEX-LENGTH (cdr lst))))
(t (+ (COMPLEX-LENGTH (car lst))
(COMPLEX-LENGTH (cdr lst))
)
)
)
)