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

前端 未结 2 1138
死守一世寂寞
死守一世寂寞 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:19

    Because of laziness. You return from binding before the sequence is realized. Therefore, the lazy sequence never sees the bindings you set. One solution would be to force realization with a doall on the sequence inside the binding.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题