2

Anything wrong with the code? looks like binding doesn't work with iterate?

(def ^:dynamic *step* 1)

(defn incr [n] (+ n *step*))

(take 3 (binding [*step* 2] (iterate incr 1)))

gives

'(1 2 3)

not

'(1 3 5)

1 Answer 1

7

The problem is that iterate returns a lazy sequence. So, the first call to incr function occurs outside of binding scope when you're trying to print the sequence.

Technically, your incr function is not free from side-effects just because it uses ^:dynamic variable.

If you want to use binding with lazy sequences you should force the evaluation of your sequence somewhere inside of a binding scope, e.g.:

(binding [*step* 2]
  (doall (take 3 (iterate incr 1))))
; => (1 3 5)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.