【问题标题】:clojure reduced not terminating reduce functionclojure 减少不终止减少功能
【发布时间】: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 函数。

【问题讨论】:

    标签: clojure reduce


    【解决方案1】:

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

    1. if - 我将 [balanced stack2] 移至 else 部分。否则reduced 将永远不会被检测到。
    2. 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。谢谢!
    猜你喜欢
    • 2018-10-29
    • 2014-09-26
    • 2016-03-26
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多