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

Yur*_*rev 4 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) ?)))
Run Code Online (Sandbox Code Playgroud)

UPDATE

以下是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))
Run Code Online (Sandbox Code Playgroud)

运行测试不会打印任何内容.使用doall结果内存不足异常.

Jan*_*Jan 5

不应该map解决问题吗?

(defn call-function-with-side-effects []
  (take-while true? (map function-with-side-effects (iterate inc 0))))
Run Code Online (Sandbox Code Playgroud)

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

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

请注意,我true在第二行中替换了true?假设这就是你的意思.