The problem is that take-while is lazy, so it does not actually perform the
"taking" operation until the lazy-seq it returns is realized, e.g. by being
printed. So when your code binds the (take-while ...) expression to "i",
the anonymous function you provided is not yet being invoked, and thus the
atom's value is not being incremented.
Since your code dereferences the "a" atom before it forces evaluation of
the "i" lazy-seq, it gets the value 0. The "a" atom's value will only be 5
after "i" has been fully realized, which happens later.
So, for example, if you changed your code to this:
(let [a (atom 0)
i (take-while (fn[x] (swap! a inc) (< x 100)) [1 2 3 4 5])]
(println i)
(println @a))
You will see the result you expect, because println forces "i" to be fully
realized, and thus "a" will be changed as a side-effect.
In general, performing side-effecty operations inside lazy code is not
usually advisable, because due to the nature of laziness, the results will
not be what you'd expect if you were coming from a, say,
imperative-language background.
Perhaps someone else can provide a link to some good reading material for
learning about laziness?
>
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en