Clojure减少不终止减少功能

时间:2019-11-30 03:43:02

标签: clojure reduce

在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 函数。

1 个答案:

答案 0 :(得分:3)

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

  1. if-我将[balanced stack2]移到了else部分。否则,将永远不会检测到reduced
  2. def-def内部的fn应替换为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]]