这是一个真正的边缘情况,可能不值得太多关注。我曾经尝试用减少而不是序列的方式编写一个 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) 参数数量不正确(1)传递给:clojure.core/preserving-reduced/fn--8743
如果 preserving-reduced 被赋予单个参数的函数长度,则不会抛出异常,例如
`
(defn ^:private preserving-reduced
[rf]
(fn ( [rval] rval)
( [rval x]
(let [ret (rf rval x)]
(if (reduced? ret)
(reduced ret)
ret)))))
`