aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/math/random.lux
blob: 8f2ef60062945cffbc21a33d523aee1fb2528b11 (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
(.module: {#.doc "Pseudo-random number generation (PRNG) algorithms."}
  [lux (#- or and list i64 nat int rev char)
   [abstract
    [functor (#+ Functor)]
    [apply (#+ Apply)]
    ["." monad (#+ do Monad)]
    hash]
   [data
    ["." product]
    ["." maybe]
    [number (#+ hex)
     ["." i64]
     ["n" nat]
     ["i" int]
     ["r" ratio]
     ["c" complex]
     ["f" frac]]
    ["." text (#+ Char) ("#@." monoid)
     ["." unicode]]
    [collection
     ["." list ("#@." fold)]
     ["." array (#+ Array)]
     ["." dictionary (#+ Dictionary)]
     ["." queue (#+ Queue)]
     ["." set (#+ Set)]
     ["." stack (#+ Stack)]
     ["." row (#+ Row)]
     [tree
      ["." finger (#+ Tree)]]]]
   [time
    ["." instant (#+ Instant)]
    ["." date (#+ Date)]
    ["." duration (#+ Duration)]
    ["." month (#+ Month)]
    ["." day (#+ Day)]]
   [type
    [refinement (#+ Refiner Refined)]]])

(type: #export #rec PRNG
  {#.doc "An abstract way to represent any PRNG."}
  (-> Any [PRNG I64]))

(type: #export (Random a)
  {#.doc "A producer of random values based on a PRNG."}
  (-> PRNG [PRNG a]))

(structure: #export functor
  (Functor Random)
  
  (def: (map f fa)
    (function (_ state)
      (let [[state' a] (fa state)]
        [state' (f a)]))))

(structure: #export apply
  (Apply Random)
  
  (def: &functor ..functor)

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

(structure: #export monad
  (Monad Random)
  
  (def: &functor ..functor)

  (def: (wrap a)
    (function (_ state)
      [state a]))

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

(def: #export (filter pred gen)
  {#.doc "Retries the generator until the output satisfies a predicate."}
  (All [a] (-> (-> a Bit) (Random a) (Random a)))
  (do ..monad
    [sample gen]
    (if (pred sample)
      (wrap sample)
      (filter pred gen))))

(def: #export (one check random)
  (All [a b]
    (-> (-> a (Maybe b)) (Random a) (Random b)))
  (do ..monad
    [sample random]
    (case (check sample)
      (#.Some output)
      (wrap output)

      #.None
      (one check random))))

(def: #export (refine refiner gen)
  {#.doc "Retries the generator until the output can be refined."}
  (All [t r] (-> (Refiner t r) (Random t) (Random (Refined t r))))
  (do ..monad
    [sample gen]
    (case (refiner sample)
      (#.Some refined)
      (wrap refined)

      #.None
      (refine refiner gen))))

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

(def: #export i64
  (Random I64)
  (function (_ prng)
    (let [[prng left] (prng [])
          [prng right] (prng [])]
      [prng (|> left
                (i64.left-shift 32)
                ("lux i64 +" right))])))

(template [<name> <type> <cast>]
  [(def: #export <name>
     (Random <type>)
     (:: ..monad map <cast> ..i64))]

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

(def: #export frac
  (Random Frac)
  (:: ..monad map (|>> .i64 f.from-bits) ..nat))

(def: #export safe-frac
  (Random Frac)
  (let [mantissa-range (.int (i64.left-shift 53 1))
        mantissa-max (i.frac (dec mantissa-range))]
    (:: ..monad map
        (|>> (i.% mantissa-range)
             i.frac
             (f./ mantissa-max))
        ..int)))

(def: #export (char set)
  (-> unicode.Set (Random Char))
  (let [[start end] (unicode.range set)
        size (n.- start end)
        in-range (: (-> Char Char)
                    (|>> (n.% size) (n.+ start)))]
    (|> ..nat
        (:: ..monad map in-range)
        (..filter (unicode.member? set)))))

(def: #export (text char-gen size)
  (-> (Random Char) Nat (Random Text))
  (if (n.= 0 size)
    (:: ..monad wrap "")
    (do ..monad
      [x char-gen
       xs (text char-gen (dec size))]
      (wrap (text@compose (text.from-code x) xs)))))

(template [<name> <set>]
  [(def: #export <name>
     (-> Nat (Random Text))
     (text (char <set>)))]

  [unicode           unicode.full]
  [ascii             unicode.ascii]
  [ascii/alpha       unicode.ascii/alpha]
  [ascii/alpha-num   unicode.ascii/alpha-num]
  [ascii/upper-alpha unicode.ascii/upper-alpha]
  [ascii/lower-alpha unicode.ascii/lower-alpha]
  )

(template [<name> <type> <ctor> <gen>]
  [(def: #export <name>
     (Random <type>)
     (do ..monad
       [left <gen>
        right <gen>]
       (wrap (<ctor> left right))))]

  [ratio   r.Ratio   r.ratio   ..nat]
  [complex c.Complex c.complex ..safe-frac]
  )

(def: #export (and left right)
  {#.doc "Sequencing combinator."}
  (All [a b] (-> (Random a) (Random b) (Random [a b])))
  (do ..monad
    [=left left
     =right right]
    (wrap [=left =right])))

(def: #export (or left right)
  {#.doc "Heterogeneous alternative combinator."}
  (All [a b] (-> (Random a) (Random b) (Random (| a b))))
  (do {! ..monad}
    [? bit]
    (if ?
      (do !
        [=left left]
        (wrap (0 #0 =left)))
      (do !
        [=right right]
        (wrap (0 #1 =right))))))

(def: #export (either left right)
  {#.doc "Homogeneous alternative combinator."}
  (All [a] (-> (Random a) (Random a) (Random a)))
  (do ..monad
    [? bit]
    (if ?
      left
      right)))

(def: #export (rec gen)
  {#.doc "A combinator for producing recursive random generators."}
  (All [a] (-> (-> (Random a) (Random a)) (Random a)))
  (function (_ state)
    (let [gen' (gen (rec gen))]
      (gen' state))))

(def: #export (maybe value-gen)
  (All [a] (-> (Random a) (Random (Maybe a))))
  (do {! ..monad}
    [some? bit]
    (if some?
      (do !
        [value value-gen]
        (wrap (#.Some value)))
      (wrap #.None))))

(template [<name> <type> <zero> <plus>]
  [(def: #export (<name> size value-gen)
     (All [a] (-> Nat (Random a) (Random (<type> a))))
     (if (n.> 0 size)
       (do ..monad
         [x value-gen
          xs (<name> (dec size) value-gen)]
         (wrap (<plus> x xs)))
       (:: ..monad wrap <zero>)))]

  [list     List   (.list)      #.Cons]
  [row Row row.empty row.add]
  )

(template [<name> <type> <ctor>]
  [(def: #export (<name> size value-gen)
     (All [a] (-> Nat (Random a) (Random (<type> a))))
     (do ..monad
       [values (list size value-gen)]
       (wrap (|> values <ctor>))))]

  [array Array array.from-list]
  [queue Queue queue.from-list]
  [stack Stack (list@fold stack.push stack.empty)]
  )

(def: #export (set Hash<a> size value-gen)
  (All [a] (-> (Hash a) Nat (Random a) (Random (Set a))))
  (if (n.> 0 size)
    (do {! ..monad}
      [xs (set Hash<a> (dec size) value-gen)]
      (loop [_ []]
        (do !
          [x value-gen
           #let [xs+ (set.add x xs)]]
          (if (n.= size (set.size xs+))
            (wrap xs+)
            (recur [])))))
    (:: ..monad wrap (set.new Hash<a>))))

(def: #export (dictionary Hash<a> 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<a> (dec size) key-gen value-gen)]
      (loop [_ []]
        (do !
          [k key-gen
           v value-gen
           #let [kv+ (dictionary.put k v kv)]]
          (if (n.= size (dictionary.size kv+))
            (wrap kv+)
            (recur [])))))
    (:: ..monad wrap (dictionary.new Hash<a>))))

(def: #export instant
  (Random Instant)
  (:: ..monad map instant.from-millis ..int))

(def: #export date
  (Random Date)
  (:: ..monad map instant.date ..instant))

(def: #export duration
  (Random Duration)
  (:: ..monad map duration.from-millis ..int))

(def: #export month
  (Random Month)
  (let [(^open "/@.") ..monad]
    (..either (..either (..either (/@wrap #month.January)
                                  (..either (/@wrap #month.February)
                                            (/@wrap #month.March)))
                        (..either (/@wrap #month.April)
                                  (..either (/@wrap #month.May)
                                            (/@wrap #month.June))))
              (..either (..either (/@wrap #month.July)
                                  (..either (/@wrap #month.August)
                                            (/@wrap #month.September)))
                        (..either (/@wrap #month.October)
                                  (..either (/@wrap #month.November)
                                            (/@wrap #month.December)))))))

(def: #export day
  (Random Day)
  (let [(^open "/@.") ..monad]
    (..either (..either (/@wrap #day.Sunday)
                        (..either (/@wrap #day.Monday)
                                  (/@wrap #day.Tuesday)))
              (..either (..either (/@wrap #day.Wednesday)
                                  (/@wrap #day.Thursday))
                        (..either (/@wrap #day.Friday)
                                  (/@wrap #day.Saturday))))))

(def: #export (run prng calc)
  (All [a] (-> PRNG (Random a) [PRNG a]))
  (calc prng))

(def: pcg-32-magic Nat 6364136223846793005)

(def: #export (pcg-32 [increase seed])
  {#.doc (doc "An implementation of the PCG32 algorithm."
              "For more information, please see: http://www.pcg-random.org/")}
  (-> [(I64 Any) (I64 Any)] PRNG)
  (function (_ _)
    [(|> seed .nat (n.* ..pcg-32-magic) ("lux i64 +" increase) [increase] pcg-32)
     (let [rot (|> seed .i64 (i64.logic-right-shift 59))]
       (|> seed
           (i64.logic-right-shift 18)
           (i64.xor seed)
           (i64.logic-right-shift 27)
           (i64.rotate-right rot)
           .i64))]))

(def: #export (xoroshiro-128+ [s0 s1])
  {#.doc (doc "An implementation of the Xoroshiro128+ algorithm."
              "For more information, please see: http://xoroshiro.di.unimi.it/")}
  (-> [(I64 Any) (I64 Any)] PRNG)
  (function (_ _)
    [(let [s01 (i64.xor s0 s1)]
       (xoroshiro-128+ [(|> s0
                            (i64.rotate-left 55)
                            (i64.xor s01)
                            (i64.xor (i64.left-shift 14 s01)))
                        (i64.rotate-left 36 s01)]))
     ("lux i64 +" s0 s1)]))