4

Looking for a way to generate a collection of return values from a function with side effects, so that I could feed it to 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) ?)))

UPDATE

Here is what I have after Jan's answer:

(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))

Running the test doesn't print anything. Using doall results in out of memory exception.

Yuriy Zubarev
  • 2,821
  • 18
  • 24

1 Answers1

5

Shouldn't a map solve the problem?

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

If you want all side effects to take effect use doall. Related: 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)))))

Mind that I replaced the true in the second line with true? assuming that this was what you meant.

Community
  • 1
  • 1
Jan
  • 11,636
  • 38
  • 47