aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/math/random.lux
blob: 7c1fbc44881f119d2c2b90b0b6ec201064000990 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
(.require
 [library
  [lux (.except or and list i64 nat int rev char only)
   [abstract
    [hash (.only Hash)]
    [functor (.only Functor)]
    [apply (.only Apply)]
    ["[0]" monad (.only Monad do)]]
   [data
    ["[0]" text (.use "[1]#[0]" monoid)
     [char (.only Char)]
     ["[0]" unicode
      ["[1]" set]]]
    [collection
     ["[0]" list (.use "[1]#[0]" mix)]
     ["[0]" array (.only Array)]
     ["[0]" dictionary (.only Dictionary)]
     ["[0]" queue (.only Queue)]
     ["[0]" set (.only Set)]
     ["[0]" stack (.only Stack)]
     ["[0]" sequence (.only Sequence)]
     [tree
      ["[0]" finger (.only Tree)]]]]
   [math
    [number (.only hex)
     ["n" nat]
     ["i" int]
     ["f" frac]
     ["r" ratio]
     ["c" complex]
     ["[0]" i64]]]
   [meta
    [type
     [refinement (.only Refiner Refined)]]]
   [world
    ["[0]" time (.only Time)
     ["[0]" instant (.only Instant)]
     ["[0]" date (.only Date)]
     ["[0]" duration (.only Duration)]
     ["[0]" month (.only Month)]
     ["[0]" day (.only Day)]]]]])

(type .public PRNG
  (Rec PRNG
    (-> Any [PRNG I64])))

(type .public (Random a)
  (-> PRNG [PRNG a]))

(def .public functor
  (Functor Random)
  (implementation
   (def (each f fa)
     (function (_ state)
       (let [[state' a] (fa state)]
         [state' (f a)])))))

(def .public apply
  (Apply Random)
  (implementation
   (def functor ..functor)

   (def (on fa ff)
     (function (_ state)
       (let [[state' f] (ff state)
             [state'' a] (fa state')]
         [state'' (f a)])))))

(def .public monad
  (Monad Random)
  (implementation
   (def functor ..functor)

   (def (in a)
     (function (_ state)
       [state a]))

   (def (conjoint ffa)
     (function (_ state)
       (let [[state' fa] (ffa state)]
         (fa state'))))))

(def .public (only pred gen)
  (All (_ a) (-> (-> a Bit) (Random a) (Random a)))
  (do ..monad
    [sample gen]
    (if (pred sample)
      (in sample)
      (only pred gen))))

(def .public (one check random)
  (All (_ a b)
    (-> (-> a (Maybe b)) (Random a) (Random b)))
  (do ..monad
    [sample random]
    (when (check sample)
      {.#Some output}
      (in output)

      {.#None}
      (one check random))))

(def .public (refined refiner gen)
  (All (_ t r) (-> (Refiner t r) (Random t) (Random (Refined t r))))
  (do ..monad
    [sample gen]
    (when (refiner sample)
      {.#Some refined}
      (in refined)

      {.#None}
      (refined refiner gen))))

(def .public bit
  (Random Bit)
  (function (_ prng)
    (let [[prng output] (prng [])]
      [prng (|> output (i64.and 1) (n.= 1))])))

(def .public i64
  (Random I64)
  (function (_ prng)
    (let [[prng left] (prng [])
          [prng right] (prng [])]
      [prng (|> left
                (i64.left_shifted 32)
                (.i64_+# right))])))

(with_template [<name> <type> <cast>]
  [(def .public <name>
     (Random <type>)
     (at ..functor each (|>> <cast>) ..i64))]

  [nat Nat .nat]
  [int Int .int]
  [rev Rev .rev]
  )

(def .public frac
  (Random Frac)
  (at ..functor each (|>> .i64 f.of_bits) ..nat))

(def .public safe_frac
  (Random Frac)
  (let [mantissa_range (.int (i64.left_shifted 53 1))
        mantissa_max (i.frac (-- mantissa_range))]
    (at ..functor each
        (|>> (i.% mantissa_range)
             i.frac
             (f./ mantissa_max))
        ..int)))

(def .public (char set)
  (-> unicode.Set (Random Char))
  (let [start (unicode.start set)
        end (unicode.end set)
        size (n.- start end)
        in_range (is (-> Char Char)
                     (|>> (n.% size) (n.+ start)))]
    (|> ..nat
        (at ..functor each in_range)
        (..only (unicode.member? set)))))

(def .public (text char_gen size)
  (-> (Random Char) Nat (Random Text))
  (if (n.= 0 size)
    (at ..monad in "")
    (do ..monad
      [x char_gen
       xs (text char_gen (-- size))]
      (in (text#composite (text.of_char x) xs)))))

(with_template [<name> <set>]
  [(def .public <name>
     (-> Nat (Random Text))
     (..text (..char <set>)))]

  [unicode       unicode.character]
  [ascii         unicode.ascii]
  [alphabetic    unicode.alphabetic]
  [alpha_numeric unicode.alpha_numeric]
  [numeric       unicode.numeric]
  [upper_cased   unicode.upper_case]
  [lower_cased   unicode.lower_case]
  )

(with_template [<name> <type> <ctor> <gen>]
  [(def .public <name>
     (Random <type>)
     (do ..monad
       [left <gen>
        right <gen>]
       (in (<ctor> left right))))]

  [ratio   r.Ratio   r.ratio   ..nat]
  [complex c.Complex c.complex ..safe_frac]
  )

(def .public (and left right)
  (All (_ a b) (-> (Random a) (Random b) (Random [a b])))
  (function (_ prng)
    (let [[prng left] (left prng)
          [prng right] (right prng)]
      [prng [left right]])))

(def .public (or left right)
  (All (_ a b) (-> (Random a) (Random b) (Random (Or a b))))
  (function (_ prng)
    (let [[prng ?] (..bit prng)]
      (if ?
        (let [[prng left] (left prng)]
          [prng {0 #0 left}])
        (let [[prng right] (right prng)]
          [prng {0 #1 right}])))))

(def .public (either left right)
  (All (_ a) (-> (Random a) (Random a) (Random a)))
  (function (_ prng)
    (let [[prng ?] (..bit prng)]
      (if ?
        (left prng)
        (right prng)))))

(def .public (rec gen)
  (All (_ a) (-> (-> (Random a) (Random a)) (Random a)))
  (function (_ state)
    (let [gen' (gen (rec gen))]
      (gen' state))))

(def .public (maybe value_gen)
  (All (_ a) (-> (Random a) (Random (Maybe a))))
  (do [! ..monad]
    [some? bit]
    (if some?
      (do !
        [value value_gen]
        (in {.#Some value}))
      (in {.#None}))))

(def .public (list size value_gen)
  (All (_ a) (-> Nat (Random a) (Random (List a))))
  (if (n.> 0 size)
    (do ..monad
      [x value_gen
       xs (list (-- size) value_gen)]
      (in {.#Item x xs}))
    (at ..monad in (.list))))

(def .public (sequence size value_gen)
  (All (_ a) (-> Nat (Random a) (Random (Sequence a))))
  (if (n.> 0 size)
    (do ..monad
      [x value_gen
       xs (sequence (-- size) value_gen)]
      (in (sequence.suffix x xs)))
    (at ..monad in sequence.empty)))

(with_template [<name> <type> <ctor>]
  [(def .public (<name> size value_gen)
     (All (_ a) (-> Nat (Random a) (Random (<type> a))))
     (do ..monad
       [values (list size value_gen)]
       (in (|> values <ctor>))))]

  [array Array array.of_list]
  [queue Queue queue.of_list]
  [stack Stack (list#mix stack.top stack.empty)]
  )

(def .public (set hash size value_gen)
  (All (_ a) (-> (Hash a) Nat (Random a) (Random (Set a))))
  (if (n.> 0 size)
    (do [! ..monad]
      [xs (set hash (-- size) value_gen)]
      (loop (again [_ []])
        (do !
          [x value_gen
           .let [xs+ (set.has x xs)]]
          (if (n.= size (set.size xs+))
            (in xs+)
            (again [])))))
    (at ..monad in (set.empty hash))))

(def .public (dictionary hash size key_gen value_gen)
  (All (_ k v) (-> (Hash k) Nat (Random k) (Random v) (Random (Dictionary k v))))
  (if (n.> 0 size)
    (do [! ..monad]
      [kv (dictionary hash (-- size) key_gen value_gen)]
      (loop (again [_ []])
        (do !
          [k key_gen
           v value_gen
           .let [kv+ (dictionary.has k v kv)]]
          (if (n.= size (dictionary.size kv+))
            (in kv+)
            (again [])))))
    (at ..monad in (dictionary.empty hash))))

(def .public instant
  (Random Instant)
  (at ..functor each instant.of_millis ..int))

(def .public date
  (Random Date)
  (at ..functor each instant.date ..instant))

(def .public time
  (Random Time)
  (at ..functor each instant.time ..instant))

(def .public duration
  (Random Duration)
  (at ..functor each duration.of_millis ..int))

(def .public month
  (Random Month)
  (let [(open "_#[0]") ..monad]
    (..either (..either (..either (_#in {month.#January})
                                  (..either (_#in {month.#February})
                                            (_#in {month.#March})))
                        (..either (_#in {month.#April})
                                  (..either (_#in {month.#May})
                                            (_#in {month.#June}))))
              (..either (..either (_#in {month.#July})
                                  (..either (_#in {month.#August})
                                            (_#in {month.#September})))
                        (..either (_#in {month.#October})
                                  (..either (_#in {month.#November})
                                            (_#in {month.#December})))))))

(def .public day
  (Random Day)
  (let [(open "_#[0]") ..monad]
    (..either (..either (_#in {day.#Sunday})
                        (..either (_#in {day.#Monday})
                                  (_#in {day.#Tuesday})))
              (..either (..either (_#in {day.#Wednesday})
                                  (_#in {day.#Thursday}))
                        (..either (_#in {day.#Friday})
                                  (_#in {day.#Saturday}))))))

(def .public (result prng calc)
  (All (_ a) (-> PRNG (Random a) [PRNG a]))
  (calc prng))

(def .public (prng update return)
  (All (_ a) (-> (-> a a) (-> a I64) (-> a PRNG)))
  (function (again state)
    (function (_ _)
      [(again (update state))
       (return state)])))

(def .public (pcg_32 [increase seed])
  (-> [(I64 Any) (I64 Any)] PRNG)
  (let [magic 6364136223846793005]
    (function (_ _)
      [(|> seed .nat (n.* magic) (.i64_+# increase) [increase] pcg_32)
       (let [rot (|> seed .nat (i64.right_shifted 59))]
         (|> seed
             (i64.right_shifted 18)
             (i64.xor seed)
             (i64.right_shifted 27)
             (i64.right_rotated rot)
             .i64))])))

(def .public (xoroshiro_128+ [s0 s1])
  (-> [(I64 Any) (I64 Any)] PRNG)
  (function (_ _)
    [(let [s01 (i64.xor s0 s1)]
       (xoroshiro_128+ [(|> s0
                            (i64.left_rotated 55)
                            (i64.xor s01)
                            (i64.xor (i64.left_shifted 14 s01)))
                        (i64.left_rotated 36 s01)]))
     (.i64_+# s0 s1)]))

... https://en.wikipedia.org/wiki/Xorshift#Initialization
... http://xorshift.di.unimi.it/splitmix64.c
(def .public split_mix_64
  (-> Nat PRNG)
  (let [twist (is (-> Nat Nat Nat)
                  (function (_ shift value)
                    (i64.xor (i64.right_shifted shift value)
                             value)))
        mix n.*]
    (..prng (n.+ (hex "9E,37,79,B9,7F,4A,7C,15"))
            (|>> (twist 30)
                 (mix (hex "BF,58,47,6D,1C,E4,E5,B9"))

                 (twist 27)
                 (mix (hex "94,D0,49,BB,13,31,11,EB"))

                 (twist 31)
                 .i64))))