tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

93 lignes · 2698 octetsBrut · Historique
1// std/random (ADR 0036): the runtime's handler, and seeded handlers whose
2// results are the same on every backend and every run (checked against a
3// separate model of SplitMix64 and of each function).
4
5import std/bytes as raw
6import std/int as bits
7import std/io
8import std/list
9import std/random.{type random, bytes}
10import std/ref
11import std/string
12
13/// `action` with `random.bytes` answered from `script`, one list per call.
14fn scripted ::
15 script: List<List<Int>>
16 action: fn() -> a / <random | e>
17 -> a / <e>
18{
19 region
20 {
21 let rest = ref.new script
22 handle
23 {
24 action ()
25 }
26 with
27 { bytes _ -> match ref.get rest
28 { [next, ..later] ->
29 {
30 ref.set rest later
31 raw.from_list next
32 }
33 , [] -> panic "the script ran out"
34 }
35 }
36 }
37}
38
39fn dice :: n: Int -> List<Int> / <random>
40{
41 list.map (list.range 1 n) fn _ { random.range 1 6 }
42}
43
44pub fn main :: -> () / <io, random>
45{
46 // The runtime's handler: random, so only properties.
47 let token = random.token 16
48 io.println "{string.length token} {token != random.token 16}"
49 let n = random.int 10
50 io.println "{n >= 0 && n < 10} {random.int 1}"
51 let f = random.float ()
52 io.println "{f >= 0.0 && f < 1.0}"
53 io.println "{list.length (random.shuffle (list.range 1 50))}"
54 io.println "{raw.length (random.bytes 0)} {raw.length (random.bytes 1000)}"
55
56 // Seeded: the same values everywhere.
57 io.println "{random.with_seed 42 fn { random.int 1000 }}"
58 io.println "{random.with_seed 42 fn { dice 10 }}"
59 io.println "{random.with_seed 1 fn { random.range (-5) 5 }}"
60 io.println "{random.with_seed 2 fn { random.float () }}"
61 io.println
62 "{random.with_seed 3 fn { random.shuffle [1, 2, 3, 4, 5, 6, 7, 8] }}"
63 io.println "{random.with_seed 4 fn { random.choice ["a", "b", "c"] }}"
64 let none: Option<Int> = random.with_seed 4 fn { random.choice [] }
65 io.println "{none}"
66 io.println "{random.with_seed 5 fn { random.token 10 }}"
67 io.println "{random.with_seed 6 fn { random.int (bits.shift_left 1 100) }}"
68 io.println "{random.with_seed (-1) fn { raw.to_list (random.bytes 3) }}"
69 io.println
70 "{random.with_seed 7 fn { random.int 1000 } == random.with_seed 7 fn { random.int 1000 }}"
71
72 // Rejection sampling: `int(3)` reads 2 bits; 3 is drawn again.
73 io.println "{scripted [[0x03], [0x01]] fn { random.int 3 }}"
74 io.println "{scripted [[0xFF, 0x05]] fn { random.int 300 }}"
75}
76//> 32 True
77//> True 0
78//> True
79//> 50
80//> 0 1000
81//> 366
82//> [6, 4, 3, 5, 3, 6, 5, 6, 5, 3]
83//> -4
84//> 0.8060087628820914
85//> [8, 5, 4, 3, 1, 7, 2, 6]
86//> Some(c)
87//> None
88//> 5ac389a30c3b0363f836
89//> 69614396455132051193203866034
90//> [32, 44, 101]
91//> True
92//> 1
93//> 261