diff --git a/core/Random.carp b/core/Random.carp index e421289e..d7eaa8d7 100644 --- a/core/Random.carp +++ b/core/Random.carp @@ -27,12 +27,28 @@ (set! s (mod (+ (* s a) c) m)) (/ s m))) - (private _) (hidden _) (doc _ "forces reseeding based on the current time at program start") - (def _ (do (seed) 0)) + (def _ (do (seed) true)) + + (doc gen-seed-at-startup "toggles reseeding the random number generator at startup.") + (defmacro gen-seed-at-startup [toggle] + (if toggle + (eval '(defmodule Random (def _ (do (seed) true)))) + (eval '(defmodule Random (def _ (do false)))))) + + (doc gen-seed-at-startup? "checks whether the random number generator was reseeded at startup. + +Use `Dynamic.Random.gen-seed-at-startup?` to check this in dynamic code.") + (defn gen-seed-at-startup? [] _) ) +(defmodule Dynamic + (defmodule Random + (doc gen-seed-at-startup? "checks whether the random number generator will be reseeded at startup.") + (defmacro gen-seed-at-startup? [] + (last (last (s-expr Random._)))))) + (defmodule Int (defn random-between [lower upper] (let [diff (- upper lower)] diff --git a/test/random-seed.carp b/test/random-seed.carp new file mode 100644 index 00000000..d905314a --- /dev/null +++ b/test/random-seed.carp @@ -0,0 +1,35 @@ +(load "Test.carp") + +(use-all Random Test) + +(def reseed-before? (Dynamic.Random.gen-seed-at-startup?)) + +(Random.gen-seed-at-startup false) + +(def reseed-after? (Dynamic.Random.gen-seed-at-startup?)) + +(Random.gen-seed-at-startup true) + +(def reseed-redo? (Dynamic.Random.gen-seed-at-startup?)) + +(Random.gen-seed-at-startup false) + +(deftest test + (assert-true test + reseed-before? + "reseeding is on by default") + (assert-false test + reseed-after? + "reseeding can be disabled") + (assert-true test + reseed-redo? + "reseeding can be re-enabled") + (assert-op test + 0.658908 ; will always be the initial if not reseeded + (Random.random) + "deterministic randomization works as expected" + Double.approx) + (assert-false test + (Random.gen-seed-at-startup?) + "reseed can be checked statically as well") +)