Sam R.
Sam R.

Reputation: 16450

difference between `iterate` and `repeatedly`

I'm new to clojure/clojurescript and trying to figure out why this function always returns 100 as the first random integer and a few zeros at the end:

(take 10 (iterate rand-int 100))
;; (100 30 19 15 4 3 2 0 0 0)

But this works as expected:

(take 10 (repeatedly #(rand-int 100)))
;; (14 14 16 92 10 69 85 74 65 95)

But then if I use anonymous fn with iterate I get nil as first value but the rest looks OK:

(take 10 (iterate #(rand-int 100)))
;; (nil 27 19 76 70 40 63 72 32 55)

Upvotes: 1

Views: 94

Answers (1)

Lee
Lee

Reputation: 144136

iterate returns the sequence (x (f x) (f (f x)) ...) so the first element is the 100 you provide. The second element is the result of (rand-int 100) which returns a random number in the range (0, 99]. In this case it returned 30 so the third element is the result of (rand-int 30) which returns an element in the range (0, 29]. Since the range is reducing, the generated numbers rapidly approach 0.

In contrast repeatedly returns the sequence ((f) (f) (f)...) where f is a function of no arguments like #(rand-int 100) where the range of generated numbers is always (0, 99]. f is expected to have some side-effect (modifying the state of the random number generator)

Upvotes: 12

Related Questions