如何从具有副作用的函数中获取返回值的集合?

时间:2013-01-03 15:22:25

标签: clojure

寻找一种从具有副作用的函数生成返回值集合的方法,以便我可以将其提供给take-while

(defn function-with-side-effects [n]
  (if (> n 10) false (do (perform-io n) true)))

(defn call-function-with-side-effects []
  (take-while true (? (iterate inc 0) ?)))

更新

以下是Jan回答后的内容:

(defn function-with-side-effects [n]
  (if (> n 10) false (do (println n) true)))

(defn call-function-with-side-effects []
  (take-while true? (map function-with-side-effects (iterate inc 0))))

(deftest test-function-with-side-effects
  (call-function-with-side-effects))

运行测试不会打印任何内容。使用doall会导致内存不足异常。

1 个答案:

答案 0 :(得分:5)

map不应该解决问题吗?

(defn call-function-with-side-effects []
  (take-while true? (map function-with-side-effects (iterate inc 0))))

如果您希望所有副作用生效,请使用doall。相关:How to convert lazy sequence to non-lazy in Clojure

(defn call-function-with-side-effects []
  (doall (take-while true? (map function-with-side-effects (iterate inc 0)))))

请注意,我将true替换为true?,假设这就是您的意思。

相关问题