(defn multiply-xf
[]
(fn [xf]
(let [product (volatile! 1)]
(fn
([] (xf))
([result]
(xf result @product)
(xf result))
([result input]
(let [new-product (* input @product)]
(vreset! product new-product)
(if (zero? new-product)
(do
(println "reduced")
(reduced ...)) <----- ???
result))))))) 这是一个简单的换能器,它是数的倍数。我想知道允许提前终止的reduced值是什么?
我试过(transient []),但这意味着换能器只适用于矢量。
发布于 2018-01-06 14:32:14
我假设您希望这个传感器产生一个正在运行的产品序列,并且在产品达到零的情况下提前终止。尽管在示例中,在2-分支步骤函数中从未调用约简函数xf,但在完成性中,它被调用了两次。
(defn multiply-xf
[]
(fn [rf]
(let [product (volatile! 1)]
(fn
([] (rf))
([result] (rf result))
([result input]
(let [new-product (vswap! product * input)]
(if (zero? new-product)
(reduced result)
(rf result new-product))))))))注意,对于早期终止,我们不关心result是什么。这是简化函数rf a.k.a xf在您的示例中的责任。我还将vreset!/@product与vswap!合并。
(sequence (multiply-xf) [2 2 2 2 2])
=> (2 4 8 16 32)如果正在运行的产品达到零,它将终止:
(sequence (multiply-xf) [2 2 0 2 2])
=> (2 4)我们可以使用transduce对输出进行求和。这里的简化功能是+,但是您的换能器不需要知道这方面的任何信息:
(transduce (multiply-xf) + [2 2 2 2])
=> 30我试过
(transient []),但这意味着换能器只适用于矢量。
这个换能器也不需要考虑它给出的序列/集合的类型。
(eduction (multiply-xf) (range 1 10))
=> (1 2 6 24 120 720 5040 40320 362880)
(sequence (multiply-xf) '(2.0 2.0 0.5 2 1/2 2 0.5))
=> (2.0 4.0 2.0 4.0 2.0 4.0 2.0)
(into #{} (multiply-xf) [2.0 2.0 0.5 2 1/2 2 0.5])
=> #{2.0 4.0}没有换能器也可以做到这一点:
(take-while (complement zero?) (reductions * [2 2 0 2 2]))
=> (2 4)https://stackoverflow.com/questions/48126441
复制相似问题