aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/math/random.lux
blob: 695323c982b13584b86961e0b2f1e0f8aa1f01d3 (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
(.module: {#.doc "Pseudo-random number generation (PRNG) algorithms."}
  [lux #- list]
  (lux (control [functor #+ Functor]
                [apply #+ Apply]
                [monad #+ do Monad]
                hash)
       (data [bit]
             [text "text/" Monoid<Text>]
             [product]
             [maybe]
             [number #+ hex]
             (number ["r" ratio]
                     ["c" complex])
             (coll [list "list/" Fold<List>]
                   [array]
                   (dictionary ["dict" unordered #+ Dict])
                   [queue #+ Queue]
                   (set ["set" unordered #+ Set])
                   [stack #+ Stack]
                   [sequence #+ Sequence]))
       ))

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

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

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

(struct: #export _ (Apply Random)
  (def: functor Functor<Random>)

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

(struct: #export _ (Monad Random)
  (def: functor Functor<Random>)

  (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 Bool) (Random a) (Random a)))
  (do Monad<Random>
    [sample gen]
    (if (pred sample)
      (wrap sample)
      (filter pred gen))))

(def: #export nat
  (Random Nat)
  (function (_ prng)
    (let [[prng left] (prng [])
          [prng right] (prng [])]
      [prng (n/+ (bit.left-shift +32 left)
                 right)])))

(def: #export int
  (Random Int)
  (:: Monad<Random> map nat-to-int nat))

(def: #export bool
  (Random Bool)
  (function (_ prng)
    (let [[prng output] (prng [])]
      [prng (|> output (bit.and +1) (n/= +1))])))

(def: (bits n)
  (-> Nat (Random Nat))
  (function (_ prng)
    (let [[prng output] (prng [])]
      [prng (bit.logical-right-shift (n/- n +64) output)])))

(def: #export frac
  (Random Frac)
  (do Monad<Random>
    [left (bits +26)
     right (bits +27)]
    (wrap (|> right
              (n/+ (bit.left-shift +27 left))
              nat-to-int
              int-to-frac
              (f// (|> +1 (bit.left-shift +53) nat-to-int int-to-frac))))))

(def: #export deg
  (Random Deg)
  (:: Monad<Random> map (|>> (:! Deg)) nat))

(def: #export (text' char-gen size)
  (-> (Random Nat) Nat (Random Text))
  (if (n/= +0 size)
    (:: Monad<Random> wrap "")
    (do Monad<Random>
      [x char-gen
       xs (text' char-gen (n/dec size))]
      (wrap (text/compose (text.from-code x) xs)))))

(type: Char-Range [Nat Nat])

(do-template [<name> <from> <to>]
  [(def: <name> Char-Range [(hex <from>) (hex <to>)])]

  [Thaana               "+0780" "+07BF"]
  [Khmer-Symbols        "+19E0" "+19FF"]
  [Phonetic-Extensions "+1D00" "+1D7F"]
  [Hangul-Syllables     "+AC00" "+D7AF"]

  [Cypriot-Syllabary                       "+10800" "+1083F"]
  [Tai-Xuan-Jing-Symbols                   "+1D300" "+1D35F"]
  [Mathematical-Alphanumeric-Symbols       "+1D400" "+1D7FF"]
  [CJK-Unified-Ideographs-Extension-B      "+20000" "+2A6DF"]
  [CJK-Compatibility-Ideographs-Supplement "+2F800" "+2FA1F"]
  )

(def: (within? [from to] char)
  (-> Char-Range Nat Bool)
  (and (n/>= from char) (n/<= to char)))

(def: unicode-ceiling (n/inc (product.right CJK-Compatibility-Ideographs-Supplement)))

(def: #export unicode
  (Random Nat)
  (|> ..nat
      (:: Monad<Random> map (n/% unicode-ceiling))
      (..filter (function (_ raw)
                  ## From "Basic Latin" to "Syriac"
                  (or (n/<= (hex "+074F") raw)
                      (within? Thaana raw)
                      ## From "Devanagari" to "Ethiopic"
                      (and (n/>= (hex "+0900") raw)
                           (n/<= (hex "+137F") raw))
                      ## From "Cherokee" to "Mongolian"
                      (and (n/>= (hex "+13A0") raw)
                           (n/<= (hex "+18AF") raw))
                      ## From "Limbu" to "Tai Le"
                      (and (n/>= (hex "+1900") raw)
                           (n/<= (hex "+197F") raw))
                      (within? Khmer-Symbols raw)
                      (within? Phonetic-Extensions raw)
                      ## From "Latin Extended Additional" to "Miscellaneous Symbols and Arrows"
                      (and (n/>= (hex "+1E00") raw)
                           (n/<= (hex "+2BFF") raw))
                      ## From "CJK Radicals Supplement" to "Kangxi Radicals"
                      (and (n/>= (hex "+2E80") raw)
                           (n/<= (hex "+2FDF") raw))
                      ## From "Ideographic Description Characters" to "Bopomofo Extended"
                      (and (n/>= (hex "+2FF0") raw)
                           (n/<= (hex "+31BF") raw))
                      ## From "Katakana Phonetic Extensions" to "CJK Unified Ideographs"
                      (and (n/>= (hex "+31F0") raw)
                           (n/<= (hex "+9FAF") raw))
                      ## From "Yi Syllables" to "Yi Radicals"
                      (and (n/>= (hex "+A000") raw)
                           (n/<= (hex "+A4CF") raw))
                      (within? Hangul-Syllables raw)
                      ## From "CJK Compatibility Ideographs" to "Arabic Presentation Forms-A"
                      (and (n/>= (hex "+F900") raw)
                           (n/<= (hex "+FDFF") raw))
                      ## From "Combining Half Marks" to "Halfwidth and Fullwidth Forms"
                      (and (n/>= (hex "+FE20") raw)
                           (n/<= (hex "+FFEF") raw))
                      ## From "Linear B Syllabary" to "Aegean Numbers"
                      (and (n/>= (hex "+10000") raw)
                           (n/<= (hex "+1013F") raw))
                      ## From "Old Italic" to "Osmanya"
                      (and (n/>= (hex "+10300") raw)
                           (n/<= (hex "+104AF") raw))
                      (within? Cypriot-Syllabary raw)
                      ## From "Byzantine Musical Symbols" to "Musical Symbols"
                      (and (n/>= (hex "+1D000") raw)
                           (n/<= (hex "+1D1FF") raw))
                      (within? Tai-Xuan-Jing-Symbols raw)
                      (within? Mathematical-Alphanumeric-Symbols raw)
                      (within? CJK-Unified-Ideographs-Extension-B raw)
                      (within? CJK-Compatibility-Ideographs-Supplement raw)
                      )))))

(def: #export (text size)
  (-> Nat (Random Text))
  (text' unicode size))

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

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

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

(def: #export (alt left right)
  {#.doc "Heterogeneous alternative combinator."}
  (All [a b] (-> (Random a) (Random b) (Random (| a b))))
  (do Monad<Random>
    [? bool]
    (if ?
      (do @
        [=left left]
        (wrap (+0 =left)))
      (do @
        [=right right]
        (wrap (+1 =right))))))

(def: #export (either left right)
  {#.doc "Homogeneous alternative combinator."}
  (All [a] (-> (Random a) (Random a) (Random a)))
  (do Monad<Random>
    [? bool]
    (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<Random>
    [some? bool]
    (if some?
      (do @
        [value value-gen]
        (wrap (#.Some value)))
      (wrap #.None))))

(do-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<Random>
         [x value-gen
          xs (<name> (n/dec size) value-gen)]
         (wrap (<plus> x xs)))
       (:: Monad<Random> wrap <zero>)))]

  [list     List   (.list)      #.Cons]
  [sequence Sequence sequence.empty sequence.add]
  )

(do-template [<name> <type> <ctor>]
  [(def: #export (<name> size value-gen)
     (All [a] (-> Nat (Random a) (Random (<type> a))))
     (do Monad<Random>
       [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<Random>
      [xs (set Hash<a> (n/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<Random> wrap (set.new Hash<a>))))

(def: #export (dict Hash<a> size key-gen value-gen)
  (All [k v] (-> (Hash k) Nat (Random k) (Random v) (Random (Dict k v))))
  (if (n/> +0 size)
    (do Monad<Random>
      [kv (dict Hash<a> (n/dec size) key-gen value-gen)]
      (loop [_ []]
        (do @
          [k key-gen
           v value-gen
           #let [kv+ (dict.put k v kv)]]
          (if (n/= size (dict.size kv+))
            (wrap kv+)
            (recur [])))))
    (:: Monad<Random> wrap (dict.new Hash<a>))))

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

(def: pcg-32-magic-mult Nat +6364136223846793005)

(def: #export (pcg-32 [inc seed])
  {#.doc "An implementation of the PCG32 algorithm.

          For more information, please see: http://www.pcg-random.org/"}
  (-> [Nat Nat] PRNG)
  (function (_ _)
    (let [seed' (|> seed (n/* pcg-32-magic-mult) (n/+ inc))
          xor-shifted (|> seed (bit.logical-right-shift +18) (bit.xor seed) (bit.logical-right-shift +27))
          rot (|> seed (bit.logical-right-shift +59))]
      [(pcg-32 [inc seed']) (bit.rotate-right rot xor-shifted)]
      )))

(def: #export (xoroshiro-128+ [s0 s1])
  {#.doc "An implementation of the Xoroshiro128+ algorithm.

          For more information, please see: http://xoroshiro.di.unimi.it/"}
  (-> [Nat Nat] PRNG)
  (function (_ _)
    (let [result (n/+ s0 s1)
          s01 (bit.xor s0 s1)
          s0' (|> (bit.rotate-left +55 s0)
                  (bit.xor s01)
                  (bit.xor (bit.left-shift +14 s01)))
          s1' (bit.rotate-left +36 s01)]
      [(xoroshiro-128+ [s0' s1']) result])
    ))

(def: (swap from to vec)
  (All [a] (-> Nat Nat (Sequence a) (Sequence a)))
  (|> vec
      (sequence.put to (maybe.assume (sequence.nth from vec)))
      (sequence.put from (maybe.assume (sequence.nth to vec)))))

(def: #export (shuffle seed sequence)
  {#.doc "Shuffle a sequence randomly based on a seed value."}
  (All [a] (-> Nat (Sequence a) (Sequence a)))
  (let [_size (sequence.size sequence)
        _shuffle (monad.fold Monad<Random>
                             (function (_ idx vec)
                               (do Monad<Random>
                                 [rand nat]
                                 (wrap (swap idx (n/% _size rand) vec))))
                             sequence
                             (list.n/range +0 (n/dec _size)))]
    (|> _shuffle
        (run (pcg-32 [+123 seed]))
        product.right)))