// std/random (ADR 0036): the runtime's handler, and seeded handlers whose // results are the same on every backend and every run (checked against a // separate model of SplitMix64 and of each function). import std/bytes as raw import std/int as bits import std/io import std/list import std/random.{type random, bytes} import std/ref import std/string /// `action` with `random.bytes` answered from `script`, one list per call. fn scripted :: script: List> action: fn() -> a / -> a / { region { let rest = ref.new script handle { action () } with { bytes _ -> match ref.get rest { [next, ..later] -> { ref.set rest later raw.from_list next } , [] -> panic "the script ran out" } } } } fn dice :: n: Int -> List / { list.map (list.range 1 n) fn _ { random.range 1 6 } } pub fn main :: -> () / { // The runtime's handler: random, so only properties. let token = random.token 16 io.println "{string.length token} {token != random.token 16}" let n = random.int 10 io.println "{n >= 0 && n < 10} {random.int 1}" let f = random.float () io.println "{f >= 0.0 && f < 1.0}" io.println "{list.length (random.shuffle (list.range 1 50))}" io.println "{raw.length (random.bytes 0)} {raw.length (random.bytes 1000)}" // Seeded: the same values everywhere. io.println "{random.with_seed 42 fn { random.int 1000 }}" io.println "{random.with_seed 42 fn { dice 10 }}" io.println "{random.with_seed 1 fn { random.range (-5) 5 }}" io.println "{random.with_seed 2 fn { random.float () }}" io.println "{random.with_seed 3 fn { random.shuffle [1, 2, 3, 4, 5, 6, 7, 8] }}" io.println "{random.with_seed 4 fn { random.choice ["a", "b", "c"] }}" let none: Option = random.with_seed 4 fn { random.choice [] } io.println "{none}" io.println "{random.with_seed 5 fn { random.token 10 }}" io.println "{random.with_seed 6 fn { random.int (bits.shift_left 1 100) }}" io.println "{random.with_seed (-1) fn { raw.to_list (random.bytes 3) }}" io.println "{random.with_seed 7 fn { random.int 1000 } == random.with_seed 7 fn { random.int 1000 }}" // Rejection sampling: `int(3)` reads 2 bits; 3 is drawn again. io.println "{scripted [[0x03], [0x01]] fn { random.int 3 }}" io.println "{scripted [[0xFF, 0x05]] fn { random.int 300 }}" } //> 32 True //> True 0 //> True //> 50 //> 0 1000 //> 366 //> [6, 4, 3, 5, 3, 6, 5, 6, 5, 3] //> -4 //> 0.8060087628820914 //> [8, 5, 4, 3, 1, 7, 2, 6] //> Some(c) //> None //> 5ac389a30c3b0363f836 //> 69614396455132051193203866034 //> [32, 44, 101] //> True //> 1 //> 261