在Clojure中打印树的级别

时间:2015-11-15 17:53:30

标签: clojure

我已经环顾四周,我无法找到办法做到这一点。 我只想逐层打印一棵树。

所以'[a [b c]]会打印出来:

a
b c

1 个答案:

答案 0 :(得分:0)

如果我理解正确,这段代码应该有效:

(defn bf
  [root] 
  (if (vector? root)
    (let [roots (filterv (complement vector?) root)
          children (filterv vector? root)]
      (if-not (empty? children)
        (into [roots] (mapcat bf children))
        [roots]))
    root))

它不是懒惰的,它返回包含节点的向量向量,例如

(bf ['a ['b 'c] 'd ['e 'f]]) => [[a d] [b c] [e f]]

打印出来:

(let [xs (bf ['a ['b 'c] 'd ['e 'f]])]
   (doseq [line (map str/join xs)] ; you need to require [clojure.string :as str]
     (println line)))