Skip to content

Instantly share code, notes, and snippets.

@MarkLavrynenko
Last active August 29, 2015 14:17
Show Gist options
  • Save MarkLavrynenko/9bec7928d30a47507988 to your computer and use it in GitHub Desktop.
Save MarkLavrynenko/9bec7928d30a47507988 to your computer and use it in GitHub Desktop.
Tree Traversal Lisp
;(load "1.lsp")
(setq tree '(1 (2 5) 6 (10 (14 (25 27) 40))))
(print tree)
(defun traverse-tree(tree depth)
(if (atom tree)
(progn (funcall func tree) (return-from traverse-tree))
)
(let ((list-len (length tree)))
;(format t "~%Depth is ~0$" depth)
(unless (atom tree)
(mapcar 'traverse-tree tree (make-list list-len :initial-element (+ 1 depth)))
)
;(format t "~%Depth is ~0$" depth)
)
)
(defun flatten(list)
(let ((leafs '()))
(defun collect-leaf(leaf)
(push leaf leafs)
)
(setq func 'collect-leaf)
(traverse-tree tree 0)
(nreverse leafs)
(return-from flatten leafs)
)
)
(print (flatten tree))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment