(repeatedly f) (repeatedly n f)
Takes a function of no args, presumably with side effects, and returns an infinite (or length n if supplied) lazy sequence of calls to it
;; these two functions are equivalent
(take 5 (repeatedly #(rand-int 11)))
;;=> (6 6 3 9 8)
;; this version only returns the first five elements
(repeatedly 5 #(rand-int 11))
;;=> (1 8 6 9 6)
;; compare with repeat, which
;; only calls the 'rand-int' function once,
;; repeating the value five times.
(repeat 5 (rand-int 100))
(94 94 94 94 94)
(defn counter []
(let [tick (atom 0)]
#(swap! tick inc)))
(def tick (counter))
(take 10 (repeatedly tick))
;;=> (1 2 3 4 5 6 7 8 9 10)
;; or equivalently
(repeatedly 10 (counter))
;;=> (1 2 3 4 5 6 7 8 9 10)
;;;; If you want random values for each element in repeatedly
;; don't call rand as an argument in partial
(= true
(every? true?
[(apply = (flatten
(repeatedly 2 (partial vector (rand)))))
(apply = (flatten
(repeatedly 2 (partial (partial vector (rand))))))]))
;; but do call it within a #(...) or (fn [] ...)
(= true
(every? false?
[(apply = (repeatedly 2 rand))
(apply = (repeatedly 2 #(rand)))
(apply = (repeatedly 2 (partial rand))) ; passing the rand function works
(apply = (flatten
(repeatedly 2 (fn [] (vector (rand))))))
(apply = (flatten
(repeatedly 2 #((partial vector (rand))))))
(apply = (flatten
(repeatedly 2 #(vector (rand)))))]))