Skip to content

Instantly share code, notes, and snippets.

@wsgac
Created June 5, 2025 13:04
Show Gist options
  • Save wsgac/b7e09b631c7feb7569580ef3a73b127f to your computer and use it in GitHub Desktop.
Save wsgac/b7e09b631c7feb7569580ef3a73b127f to your computer and use it in GitHub Desktop.
Common Lisp random state
;; Stores random state in a structure SB-KERNEL::RANDOM-STATE
*random-state*
;; Get the actual state vector
(sb-kernel::random-state-state *random-state*)
;; Intercept the state vector (copying it)
(defvar *rs1* (copy-seq (sb-kernel::random-state-state *random-state*)))
;; Sample a bunch of random numbers
(loop repeat 20 collect (random 100))
;; e.g. -> (98 92 16 0 39 96 79 42 66 82 25 76 51 29 84 15 74 84 68 46)
;; run once more - different set,
;; e.g. -> (57 17 99 56 81 28 63 78 15 85 71 58 47 58 43 49 19 30 85 99)
;; Restore saved random state from the previously made copy
;; - no default way to directly copy the entire structure - need to re-create it
(setf *random-state* (sb-kernel::%make-random-state (copy-seq *rs1*)))
;; Try again - the same sequence of (pseudo)random numbers
(loop repeat 20 collect (random 100))
;; e.g. -> (98 92 16 0 39 96 79 42 66 82 25 76 51 29 84 15 74 84 68 46)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment