4

寻找一种从具有副作用的函数生成返回值集合的方法,以便我可以将其提供给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导致内存不足异常。

4

1 回答 1

5

不应该map解决问题吗?

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

如果您希望所有副作用生效,请使用doall. 相关:如何在 Clojure 中将惰性序列转换为非惰性序列

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

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

于 2013-01-03T15:36:05.603 回答