我用什么来减少这个传感器?

What do I reduce this transducer with?

(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 []) 但这意味着换能器只适用于矢量。

我假设您希望此传感器产生一个 运行 乘积序列,并在乘积达到零时提前终止。尽管在示例中,reducing 函数 xf 从未在 2-arity step 函数中被调用,并且在 completion 中被调用了两次元数。

(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!/@productvswap!.

合并
(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

I've tried (transient []) but that means the transducer only works with vectors.

这个传感器也不需要关心它所给的 sequence/collection 类型。

(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)