gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:07:37 36 4
gpt4 key购买 nike

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

最佳答案

不应该是 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? 假设这就是你的意思。

关于clojure - 如何从具有副作用的函数中获取返回值的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14141811/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com