clojure 减少不终止减少功能

Posted

技术标签:

【中文标题】clojure 减少不终止减少功能【英文标题】:clojure reduced not terminating reduce function 【发布时间】:2020-03-25 12:52:29 【问题描述】:

在 clojure 文档中它说:

用法:(减少x)

以某种方式包装 x,以使 reduce 以值 x 终止

我正在尝试从具有布尔值和向量值的 reduce 函数返回。

(def bp (reduce (fn [[balanced stack] singlenum]
    (def stack2 (conj stack singlenum))
    (println stack2)
    (if (= 2 singlenum)
      (reduced [false stack2])
    )
    [balanced stack2]
  )
  [true (vector)] [1 2 3 4]
))

bp 评估为[true [1 2 3 4]],我期待[false [1 2]]reduce 并未终止 reduce 函数。我试图用特定值终止 reduce 函数。

【问题讨论】:

【参考方案1】:

你有正确的逻辑。我刚刚修改了您对ifdef 的用法。

    if - 我将 [balanced stack2] 移至 else 部分。否则reduced 将永远不会被检测到。 def - fn 内的 def 应替换为 let
(def bp (reduce (fn [[balanced stack] singlenum]
                  (let [stack2 (conj stack singlenum)]
                       (println stack2)
                       (if (= 2 singlenum)
                         (reduced [false stack2])
                         [balanced stack2])))
                [true (vector)]
                [1 2 3 4]))
| | | | | stack=> []
| | | | | singlenum=> 1
| | | | (conj stack singlenum)=> [1]
| | | | stack2=> [1]
[1]
| | | (println stack2)=> nil
| | | | | singlenum=> 1
| | | | (= 2 singlenum)=> false
| | | | | balanced=> true
| | | | | stack2=> [1]
| | | (if (= 2 singlenum) (reduced #) [balanced stack2])=> [true [1]]
| | (let [stack2 #] (println stack2) (if # # #))=> [true [1]]
| | | | | stack=> [1]
| | | | | singlenum=> 2
| | | | (conj stack singlenum)=> [1 2]
| | | | stack2=> [1 2]
[1 2]
| | | (println stack2)=> nil
| | | | | singlenum=> 2
| | | | (= 2 singlenum)=> true
| | | | | | stack2=> [1 2]
| | | | (reduced [false stack2])=> #reduced[:status :ready, :val [false [1 2]] 0x5fbdbb78]
| | | (if (= 2 singlenum) (reduced #) [balanced stack2])=> #reduced[:status :ready, :val [false [1 2]] 0x5fbdbb78]
| | (let [stack2 #] (println stack2) (if # # #))=> #reduced[:status :ready, :val [false [1 2]] 0x5fbdbb78]
(reduce (fn # #) [true #] [1 2 3 4])=> [false [1 2]]

【讨论】:

那行得通。我在cyber-dojo.org 上做平衡括号kata,试图学习Clojure。谢谢!

以上是关于clojure 减少不终止减少功能的主要内容,如果未能解决你的问题,请参考以下文章

Clojure 在函数中减少溢出,但在直接传递给 REPL 时不会溢出

在 Clojure 中将嵌套向量减少为另一个向量

Clojure:减少大型懒惰收集会占用内存

包含混合向量和双精度的向量的 Clojure 减少函数

变压器与减速器的区别是什么? - Clojure

let 绑定中的 Clojure 函数