doseq

时间:2016-10-25 16:30:17

标签: clojure

在doseq期间更新/计算变量的最佳方法是什么?

显然我可以做以下事情:

(doseq [x xs]
        (println (string/join " " x)))
(println "total:" (reduce + 0 (map count xs)))

但我想避免在最后映射整个列表来计算一个值......在迭代时更新计数更有意义。

我发现这个有效,但它看起来有点像淤泥。

(defn display-xs [xs]
  ;; all I want to do is update a count while I print,
  ;; and have that value available afterwards!
  (let [n (ref 0)]
    (do
      (doseq [x xs]
        (dosync
         (ref-set n (+ @n (count x)))
         (println (string/join " " x))))
      (println "total:" @n))))

我知道doseq允许:let,但在doseq完成后我需要该值。

或者

(println "total:" (reduce (fn [m x] (do (println x) (+ m (count x)))) 0 xs))

3 个答案:

答案 0 :(得分:1)

你不应该担心循环的最小微不足道的开销。分离不同的任务更为重要。我非常喜欢你的第一个版本。

你的第二个版本可能看起来更好,但我还是更喜欢第一个。

(defn display-xs [xs]
  (let [n (atom 0)]
    (doseq [x xs]
      (swap! n + (count x))
      (println (string/join " " x)))
    (println "total: " @n)))

答案 1 :(得分:0)

我稍微改写了你的代码,告诉我如何做到这一点:

(def sample-vals (repeatedly 10 #(range (+ 5 (rand-int 10)))))

(defn display-xs [xs]
  (let [n (atom 0)]
    (doseq [x xs]
       (swap! n + (count x))
       (println x))
    (println "total:" @n)))

(newline)
(display-xs sample-vals)

(defn print-n-sum [cum coll]
  (let [cnt  (count coll) ]
     (printf "%4d:  " cnt)
     (println  coll)
     (+ cum cnt)))

(defn calc-sum [xs]
  (let [n (reduce print-n-sum 0 xs) ]
    (println "total:" n)))

(newline)
(calc-sum sample-vals)

结果

> rs; lein run
(0 1 2 3 4 5 6 7 8 9)
(0 1 2 3 4 5 6 7 8 9 10 11)
(0 1 2 3 4 5 6 7 8 9 10)
(0 1 2 3 4 5 6 7 8 9 10 11)
(0 1 2 3 4)
(0 1 2 3 4 5 6 7 8 9 10 11)
(0 1 2 3 4 5)
(0 1 2 3 4 5 6 7 8 9 10)
(0 1 2 3 4 5 6)
(0 1 2 3 4 5 6 7 8 9 10)
total: 97

  10:  (0 1 2 3 4 5 6 7 8 9)
  12:  (0 1 2 3 4 5 6 7 8 9 10 11)
  11:  (0 1 2 3 4 5 6 7 8 9 10)
  12:  (0 1 2 3 4 5 6 7 8 9 10 11)
   5:  (0 1 2 3 4)
  12:  (0 1 2 3 4 5 6 7 8 9 10 11)
   6:  (0 1 2 3 4 5)
  11:  (0 1 2 3 4 5 6 7 8 9 10)
   7:  (0 1 2 3 4 5 6)
  11:  (0 1 2 3 4 5 6 7 8 9 10)
total: 97

请注意,您不必使用原子(本例中比ref更简单)。您可以执行打印并添加一个功能,例如您print-n-sum提供的reduce

答案 2 :(得分:0)

您可以在减少附加功能

中打印它
(defn print-and-append [acc x]
      (println (string/join " " x))
      (+ acc (count x)))

(println (reduce print-and-append 0 xs))