tree-seq

clojure.core

  • (tree-seq branch? children root)
Returns a lazy sequence of the nodes in a tree, via a depth-first walk.
branch? must be a fn of one arg that returns true if passed a node
that can have children (but may not). children must be a fn of one
arg that returns a sequence of the children. Will only be called on
nodes for which branch? returns true. Root is the root node of the
tree.

5 Examples top

  • ;; Each node is a number or a seq, 
    ;; so branch?==seq? and children==identity
    ;; 
    ;;     .
    ;;    / \
    ;;   .   .
    ;;  /|\  |
    ;; 1 2 . 4
    ;;     |  
    ;;     3
    ;;
    
    user=> (tree-seq seq? identity '((1 2 (3)) (4)))
    
    (((1 2 (3)) (4)) (1 2 (3)) 1 2 (3) 3 (4) 4)
    
  • user=> (tree-seq map? #(interleave (keys %) (vals %)) {:a 1 :b {:c 3 :d 4 :e {:f 6 :g 7}}})
    
    ({:a 1, :b {:c 3, :d 4, :e {:f 6, :g 7}}} :a 1 :b {:c 3, :d 4, :e {:f 6, :g 7}} :c 3 :d 4 :e {:f 6, :g 7} :f 6 :g 7)
  • ;; Each node is a (node-root child1 child2 ...),
    ;; so branch?==next and children==rest
    ;;
    ;;     A
    ;;    / \
    ;;   B   C
    ;;  / \  |
    ;; D   E F
    ;;
    user=> (map first (tree-seq next rest '(:A (:B (:D) (:E)) (:C (:F)))))
    
    (:A :B :D :E :C :F)
  • ;; FYI, previous example doesn't always work:
    ;;
    user> (map first (tree-seq next rest '((1 2 (3)) (4))))
    ((1 2 (3)) 4)
    
  • user=> (tree-seq seq? seq [[1 2 [3]] [4]])
    ([[1 2 [3]] [4]])
    
    user=> (tree-seq vector? seq [[1 2 [3]] [4]])
    ([[1 2 [3]] [4]] [1 2 [3]] 1 2 [3] 3 [4] 4)
    
    user=> (tree-seq seq? seq '((1 2 (3)) (4)))
    (((1 2 (3)) (4)) (1 2 (3)) 1 2 (3) 3 (4) 4)
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:4337 top

(defn tree-seq
  "Returns a lazy sequence of the nodes in a tree, via a depth-first walk.
   branch? must be a fn of one arg that returns true if passed a node
   that can have children (but may not).  children must be a fn of one
   arg that returns a sequence of the children. Will only be called on
   nodes for which branch? returns true. Root is the root node of the
  tree."
  {:added "1.0"
   :static true}
   [branch? children root]
   (let [walk (fn walk [node]
                (lazy-seq
                 (cons node
                  (when (branch? node)
                    (mapcat walk (children node))))))]
     (walk root)))
Vars in clojure.core/tree-seq:
Used in 0 other vars

Comments top

No comments for tree-seq. Log in to add a comment.