我该如何减少这种传感器?

时间:2018-01-06 10:28:55

标签: clojure transducer

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

1 个答案:

答案 0 :(得分:1)

我假设您希望此传感器产生正在运行的产品序列,并在产品达到零时提前终止。虽然在示例中,在2-arity 步骤函数中从不调用reduce函数xf,并且在完成 arity中调用它两次。

(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
  

我已尝试(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)
相关问题