Code Red > AutoLISP (Vanilla / Visual)
Find the nest level of a list
VovKa:
could it be that there's a misprint in the book, shouldn't it be -1?
and there is no need to define max_ function, we can use built-in max instead
--- Code: ---(defun depth (x)
(cond ((atom x) -1)
(t (max (1+ (depth (car x))) (depth (cdr x))))
)
)
--- End code ---
Marc'Antonio Alessi:
--- Quote from: VovKa on October 20, 2017, 12:22:52 PM ---could it be that there's a misprint in the book, shouldn't it be -1?
and there is no need to define max_ function, we can use built-in max instead
--- Code: ---(defun depth (x)
(cond ((atom x) -1)
(t (max (1+ (depth (car x))) (depth (cdr x))))
)
)
--- End code ---
--- End quote ---
--- Code: ---(setq alist '(((((("A") ("a\"(((())))") ((1 . 2)) ))((((((((((((((((((((((("B" ("C"))))))))))))))))))))))))("C")))) ); -> 26
Elapsed milliseconds / relative speed for 65536 iteration(s):
(DEPTH ALIST).....2000 / 1.53 <fastest>
(FOO#5 ALIST).....3063 / 1 <slowest>
--- End code ---
Lee Mac:
Which is it?
--- Code - Auto/Visual Lisp: ---_$ (depth '())-1_$ (foo '())0
JohnK:
I havent read the thread but I don't think that classifies as a tree, Lee. However, I guess it's depth would technically be zero if it were classified as one. But I think I would still want my function to return -1 in the case of a null tree.
Grrr1337:
Damn I'm so close fixing this (iterative) code from reply #13:
--- Code - Auto/Visual Lisp: ---(defun NestLvl ( L / i r ) (and L (listp L) (setq i 0) (while (and L (vl-some (function vl-consp) L)) (setq L (apply (function append) (setq r ; only for debugging purpose (mapcar (function (lambda (x / v ) (cond ( (atom x) nil) ( (if (atom (setq v (cdr x))) ; dotted pair (cons (car x) (list v)) x ) ) ); cond ); lambda ); function L ); mapcar ) ) ) (setq i (1+ i)) ) ) i); defun NestLvl
--- Code - Auto/Visual Lisp: ---_$ (setq aL '( ((1 . 2)) ("a\"(((())))") "string" nil ("A" "B" "C") (("A")("B")("C")) (("A")(("B"))("C")) (("A")((((("B")))))("C")) (((("A")))((((((("B")))))))("C")) (((("A")))((((((((((((((((((((((("B" ("C"))))))))))))))))))))))))("C")) (((((("A")))((((((((((((((((((((((("B" ("C"))))))))))))))))))))))))("C")))) (("(1") "2" "3") (((1) (2) (3))) ("a\"(((())))") )) _$ (mapcar 'NestLvl aL)(1 0 nil nil 0 1 2 5 7 24 26 1 2 0)_$ (mapcar 'NestedListLevel aL)(0 0 nil nil 0 1 2 5 7 24 26 1 2 0) ; this is the correct result for referenceYet so far.
Navigation
[0] Message Index
[#] Next page
[*] Previous page
Go to full version