这是一个真实的情况,因此可能不值得过多关注。我正在尝试用reduction而不是序列来写tree-seq的一个版本。这是我找到的解决方案:
`
(defn tree-producer [branch? children node]
(let [recurse #(tree-producer branch? children %)]
(reify clojure.lang.IReduceInit
(reduce [this rf rval]
(let [rval (rf rval node)]
(cond
(reduced? rval) @rval
(branch? node) (transduce (mapcat recurse) rf rval (children node))
:else rval))))))
`
但是使用它导致了一个异常
user=> (into [] (tree-producer seq? identity '((1 2 (3)) (4)))) 运行错误 (ArityException) 在 temp$tree_producer$reify__7693/reduce (temp.clj:129)。向 clojure.core/preserving-reduced/fn--8743 过于多个参数(1)
如果给 preserving-reduced 提供一个1参数形式,则不会抛出异常,即
`
(defn ^:private preserving-reduced
[rf]
(fn ( [rval] rval)
( [rval x]
(let [ret (rf rval x)]
(if (reduced? ret)
(reduced ret)
ret)))))
`