Why doesn't repeatedly generate reproducible random numbers when using a seed in Clojure?

前端 未结 2 1140
死守一世寂寞
死守一世寂寞 2021-01-04 11:07

I have some functions that require a series of random numbers so I\'ve taken some simple primitives such as #(inc (g/uniform 0 n)) and I can\'t seem to generate

2条回答
  •  臣服心动
    2021-01-04 11:37

    If, as your comment on the other answer indicates, you want to preserve the laziness, then you would need to apply the binding in the function passed to repeatedly, capturing a seed that you created outside of the lazy seq. For instance:

    (defn rand-seq [seed]
      (let [r (java.util.Random. seed)]
        (repeatedly #(binding [g/*rnd* r]
                       (inc (g/uniform 0 10))))))
    
    (take 10 (rand-seq 42))
    #=> (8 7 4 3 7 10 4 3 5 8)
    
    (take 10 (rand-seq 42))
    #=> (8 7 4 3 7 10 4 3 5 8)
    

提交回复
热议问题