I want to be able to generate repeatable numbers using rand
in Clojure. (Specifically, I want results of calls to rand-nth
or Incanter\'s sample
From what I understand, none of the above are functional approaches. If you want that, you can use a lazy-seq:
(letfn [(f [randomizer] (lazy-seq (cons (.nextInt randomizer) (f randomizer))))]
(defn create-random
([] (f (java.util.Random.)))
([seed] (f (java.util.Random. seed)))))
To get the first random number you use:
(first (create-random 0)) ;; using 0 as seed
To get the rest of the sequence you use:
(rest (create-random 0)) ;; again 0 as seed
To get the first element and a reference to the rest you can use:
(defn pop [x (create-random 0)]
(n, rest) `(~(first x) ~(rest x)))