-
Notifications
You must be signed in to change notification settings - Fork 50
/
Stateful.hs
836 lines (758 loc) · 27 KB
/
Stateful.hs
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
-- |
-- Module : System.Random.Stateful
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file LICENSE in the 'random' repository)
-- Maintainer : libraries@haskell.org
-- Stability : stable
--
-- This library deals with the common task of pseudo-random number generation.
module System.Random.Stateful
(
-- * Pure Random Generator
module System.Random
-- * Monadic Random Generator
-- $introduction
-- * Usage
-- $usagemonadic
-- * Mutable pseudo-random number generator interfaces
-- $interfaces
, StatefulGen(..)
, FrozenGen(..)
, RandomGenM(..)
, withMutableGen
, withMutableGen_
, randomM
, randomRM
, splitGenM
, globalStdGen
-- * Monadic adapters for pure pseudo-random number generators #monadicadapters#
-- $monadicadapters
-- ** Pure adapter
, StateGen(..)
, StateGenM(..)
, runStateGen
, runStateGen_
, runStateGenT
, runStateGenT_
, runStateGenST
, runStateGenST_
-- ** Mutable adapter with atomic operations
, AtomicGen(..)
, AtomicGenM(..)
, newAtomicGenM
, applyAtomicGen
-- ** Mutable adapter in 'IO'
, IOGen(..)
, IOGenM(..)
, newIOGenM
, applyIOGen
-- ** Mutable adapter in 'ST'
, STGen(..)
, STGenM(..)
, newSTGenM
, applySTGen
, runSTGen
, runSTGen_
-- ** Mutable adapter in 'STM'
, TGen(..)
, TGenM(..)
, newTGenM
, newTGenMIO
, applyTGen
-- * Pseudo-random values of various types
-- $uniform
, Uniform(..)
, uniformListM
, uniformViaFiniteM
, UniformRange(..)
-- * Generators for sequences of pseudo-random bytes
, genShortByteStringIO
, genShortByteStringST
, uniformByteStringM
, uniformDouble01M
, uniformDoublePositive01M
, uniformFloat01M
, uniformFloatPositive01M
, uniformEnumM
, uniformEnumRM
-- * Appendix
-- ** How to implement 'StatefulGen'
-- $implementmonadrandom
-- ** Floating point number caveats #fpcaveats#
-- $floating
-- * References
-- $references
) where
import Control.DeepSeq
import Control.Monad.IO.Class
import Control.Monad.ST
import GHC.Conc.Sync (STM, TVar, newTVar, newTVarIO, readTVar, writeTVar)
import Control.Monad.State.Strict
import Data.IORef
import Data.STRef
import Foreign.Storable
import System.Random
import System.Random.Internal
-- $introduction
--
-- This module provides type classes and instances for the following concepts:
--
-- [Monadic pseudo-random number generators] 'StatefulGen' is an interface to
-- monadic pseudo-random number generators.
--
-- [Monadic adapters] 'StateGenM', 'AtomicGenM', 'IOGenM', 'STGenM` and 'TGenM'
-- turn a 'RandomGen' instance into a 'StatefulGen' instance.
--
-- [Drawing from a range] 'UniformRange' is used to generate a value of a
-- type uniformly within a range.
--
-- This library provides instances of 'UniformRange' for many common
-- numeric types.
--
-- [Drawing from the entire domain of a type] 'Uniform' is used to generate a
-- value of a type uniformly over all possible values of that type.
--
-- This library provides instances of 'Uniform' for many common bounded
-- numeric types.
--
-- $usagemonadic
--
-- In monadic code, use the relevant 'Uniform' and 'UniformRange' instances to
-- generate pseudo-random values via 'uniformM' and 'uniformRM', respectively.
--
-- As an example, @rollsM@ generates @n@ pseudo-random values of @Word@ in the
-- range @[1, 6]@ in a 'StatefulGen' context; given a /monadic/ pseudo-random
-- number generator, you can run this probabilistic computation as follows:
--
-- >>> :{
-- let rollsM :: StatefulGen g m => Int -> g -> m [Word]
-- rollsM n = replicateM n . uniformRM (1, 6)
-- in do
-- monadicGen <- MWC.create
-- rollsM 10 monadicGen :: IO [Word]
-- :}
-- [3,4,3,1,4,6,1,6,1,4]
--
-- Given a /pure/ pseudo-random number generator, you can run the monadic
-- pseudo-random number computation @rollsM@ in an 'IO' or 'ST' context by
-- applying a monadic adapter like 'AtomicGenM', 'IOGenM' or 'STGenM'
-- (see [monadic-adapters](#monadicadapters)) to the pure pseudo-random number
-- generator.
--
-- >>> :{
-- let rollsM :: StatefulGen g m => Int -> g -> m [Word]
-- rollsM n = replicateM n . uniformRM (1, 6)
-- pureGen = mkStdGen 42
-- in
-- newIOGenM pureGen >>= rollsM 10 :: IO [Word]
-- :}
-- [1,1,3,2,4,5,3,4,6,2]
-------------------------------------------------------------------------------
-- Pseudo-random number generator interfaces
-------------------------------------------------------------------------------
-- $interfaces
--
-- Pseudo-random number generators come in two flavours: /pure/ and /monadic/.
--
-- ['System.Random.RandomGen': pure pseudo-random number generators]
-- See "System.Random" module.
--
-- ['StatefulGen': monadic pseudo-random number generators] These generators
-- mutate their own state as they produce pseudo-random values. They
-- generally live in 'ST' or 'IO' or some transformer that implements
-- @PrimMonad@.
--
-------------------------------------------------------------------------------
-- Monadic adapters
-------------------------------------------------------------------------------
-- $monadicadapters
--
-- Pure pseudo-random number generators can be used in monadic code via the
-- adapters 'StateGenM', 'AtomicGenM', 'IOGenM', 'STGenM' and 'TGenM'
--
-- * 'StateGenM' can be used in any state monad. With strict 'StateT' there is
-- no performance overhead compared to using the 'RandomGen' instance
-- directly. 'StateGenM' is /not/ safe to use in the presence of exceptions
-- and concurrency.
--
-- * 'AtomicGenM' is safe in the presence of exceptions and concurrency since
-- it performs all actions atomically.
--
-- * 'IOGenM' is a wrapper around an 'IORef' that holds a pure generator.
-- 'IOGenM' is safe in the presence of exceptions, but not concurrency.
--
-- * 'STGenM' is a wrapper around an 'STRef' that holds a pure generator.
-- 'STGenM' is safe in the presence of exceptions, but not concurrency.
--
-- * 'TGenM' is a wrapper around a 'TVar' that holds a pure generator. 'TGenM'
-- can be used in a software transactional memory monad 'STM`. It is not as
-- performant as 'AtomicGenM`, but it can provide stronger guarantees in a
-- concurrent setting.
-- | Interface to operations on 'RandomGen' wrappers like 'IOGenM' and 'StateGenM'.
--
-- @since 1.2.0
class (RandomGen r, StatefulGen g m) => RandomGenM g r m | g -> r where
applyRandomGenM :: (r -> (a, r)) -> g -> m a
-- | Splits a pseudo-random number generator into two. Overwrites the mutable
-- wrapper with one of the resulting generators and returns the other.
--
-- @since 1.2.0
splitGenM :: RandomGenM g r m => g -> m r
splitGenM = applyRandomGenM split
instance (RandomGen r, MonadIO m) => RandomGenM (IOGenM r) r m where
applyRandomGenM = applyIOGen
instance (RandomGen r, MonadIO m) => RandomGenM (AtomicGenM r) r m where
applyRandomGenM = applyAtomicGen
instance (RandomGen r, MonadState r m) => RandomGenM (StateGenM r) r m where
applyRandomGenM f _ = state f
instance RandomGen r => RandomGenM (STGenM r s) r (ST s) where
applyRandomGenM = applySTGen
instance RandomGen r => RandomGenM (TGenM r) r STM where
applyRandomGenM = applyTGen
-- | Runs a mutable pseudo-random number generator from its 'FrozenGen' state.
--
-- ====__Examples__
--
-- >>> import Data.Int (Int8)
-- >>> withMutableGen (IOGen (mkStdGen 217)) (uniformListM 5) :: IO ([Int8], IOGen StdGen)
-- ([-74,37,-50,-2,3],IOGen {unIOGen = StdGen {unStdGen = SMGen 4273268533320920145 15251669095119325999}})
--
-- @since 1.2.0
withMutableGen :: FrozenGen f m => f -> (MutableGen f m -> m a) -> m (a, f)
withMutableGen fg action = do
g <- thawGen fg
res <- action g
fg' <- freezeGen g
pure (res, fg')
-- | Same as 'withMutableGen', but only returns the generated value.
--
-- ====__Examples__
--
-- >>> import System.Random.Stateful
-- >>> let pureGen = mkStdGen 137
-- >>> withMutableGen_ (IOGen pureGen) (uniformRM (1 :: Int, 6 :: Int))
-- 4
--
-- @since 1.2.0
withMutableGen_ :: FrozenGen f m => f -> (MutableGen f m -> m a) -> m a
withMutableGen_ fg action = fst <$> withMutableGen fg action
-- | Generates a list of pseudo-random values.
--
-- ====__Examples__
--
-- >>> import System.Random.Stateful
-- >>> let pureGen = mkStdGen 137
-- >>> g <- newIOGenM pureGen
-- >>> uniformListM 10 g :: IO [Bool]
-- [True,True,True,True,False,True,True,False,False,False]
--
-- @since 1.2.0
uniformListM :: (StatefulGen g m, Uniform a) => Int -> g -> m [a]
uniformListM n gen = replicateM n (uniformM gen)
-- | Generates a pseudo-random value using monadic interface and `Random` instance.
--
-- ====__Examples__
--
-- >>> import System.Random.Stateful
-- >>> let pureGen = mkStdGen 137
-- >>> g <- newIOGenM pureGen
-- >>> randomM g :: IO Double
-- 0.5728354935654512
--
-- You can use type applications to disambiguate the type of the generated numbers:
--
-- >>> :set -XTypeApplications
-- >>> randomM @Double g
-- 0.6268211351114487
--
-- @since 1.2.0
randomM :: (Random a, RandomGenM g r m) => g -> m a
randomM = applyRandomGenM random
-- | Generates a pseudo-random value using monadic interface and `Random` instance.
--
-- ====__Examples__
--
-- >>> import System.Random.Stateful
-- >>> let pureGen = mkStdGen 137
-- >>> g <- newIOGenM pureGen
-- >>> randomRM (1, 100) g :: IO Int
-- 52
--
-- You can use type applications to disambiguate the type of the generated numbers:
--
-- >>> :set -XTypeApplications
-- >>> randomRM @Int (1, 100) g
-- 2
--
-- @since 1.2.0
randomRM :: (Random a, RandomGenM g r m) => (a, a) -> g -> m a
randomRM r = applyRandomGenM (randomR r)
-- | Wraps an 'IORef' that holds a pure pseudo-random number generator. All
-- operations are performed atomically.
--
-- * 'AtomicGenM' is safe in the presence of exceptions and concurrency.
-- * 'AtomicGenM' is the slowest of the monadic adapters due to the overhead
-- of its atomic operations.
--
-- @since 1.2.0
newtype AtomicGenM g = AtomicGenM { unAtomicGenM :: IORef g}
-- | Frozen version of mutable `AtomicGenM` generator
--
-- @since 1.2.0
newtype AtomicGen g = AtomicGen { unAtomicGen :: g}
deriving (Eq, Ord, Show, RandomGen, Storable, NFData)
-- | Creates a new 'AtomicGenM'.
--
-- @since 1.2.0
newAtomicGenM :: MonadIO m => g -> m (AtomicGenM g)
newAtomicGenM = fmap AtomicGenM . liftIO . newIORef
-- | Global mutable standard pseudo-random number generator. This is the same
-- generator that was historically used by `randomIO` and `randomRIO` functions.
--
-- >>> replicateM 10 (uniformRM ('a', 'z') globalStdGen)
-- "tdzxhyfvgr"
--
-- @since 1.2.1
globalStdGen :: AtomicGenM StdGen
globalStdGen = AtomicGenM theStdGen
instance (RandomGen g, MonadIO m) => StatefulGen (AtomicGenM g) m where
uniformWord32R r = applyAtomicGen (genWord32R r)
{-# INLINE uniformWord32R #-}
uniformWord64R r = applyAtomicGen (genWord64R r)
{-# INLINE uniformWord64R #-}
uniformWord8 = applyAtomicGen genWord8
{-# INLINE uniformWord8 #-}
uniformWord16 = applyAtomicGen genWord16
{-# INLINE uniformWord16 #-}
uniformWord32 = applyAtomicGen genWord32
{-# INLINE uniformWord32 #-}
uniformWord64 = applyAtomicGen genWord64
{-# INLINE uniformWord64 #-}
uniformShortByteString n = applyAtomicGen (genShortByteString n)
instance (RandomGen g, MonadIO m) => FrozenGen (AtomicGen g) m where
type MutableGen (AtomicGen g) m = AtomicGenM g
freezeGen = fmap AtomicGen . liftIO . readIORef . unAtomicGenM
thawGen (AtomicGen g) = newAtomicGenM g
-- | Atomically applies a pure operation to the wrapped pseudo-random number
-- generator.
--
-- ====__Examples__
--
-- >>> import System.Random.Stateful
-- >>> let pureGen = mkStdGen 137
-- >>> g <- newAtomicGenM pureGen
-- >>> applyAtomicGen random g :: IO Int
-- 7879794327570578227
--
-- @since 1.2.0
applyAtomicGen :: MonadIO m => (g -> (a, g)) -> AtomicGenM g -> m a
applyAtomicGen op (AtomicGenM gVar) =
liftIO $ atomicModifyIORef' gVar $ \g ->
case op g of
(a, g') -> (g', a)
{-# INLINE applyAtomicGen #-}
-- | Wraps an 'IORef' that holds a pure pseudo-random number generator.
--
-- * 'IOGenM' is safe in the presence of exceptions, but not concurrency.
-- * 'IOGenM' is slower than 'StateGenM' due to the extra pointer indirection.
-- * 'IOGenM' is faster than 'AtomicGenM' since the 'IORef' operations used by
-- 'IOGenM' are not atomic.
--
-- An example use case is writing pseudo-random bytes into a file:
--
-- >>> import UnliftIO.Temporary (withSystemTempFile)
-- >>> import Data.ByteString (hPutStr)
-- >>> let ioGen g = withSystemTempFile "foo.bin" $ \_ h -> uniformRM (0, 100) g >>= flip uniformByteStringM g >>= hPutStr h
--
-- and then run it:
--
-- >>> newIOGenM (mkStdGen 1729) >>= ioGen
--
-- @since 1.2.0
newtype IOGenM g = IOGenM { unIOGenM :: IORef g }
-- | Frozen version of mutable `IOGenM` generator
--
-- @since 1.2.0
newtype IOGen g = IOGen { unIOGen :: g }
deriving (Eq, Ord, Show, RandomGen, Storable, NFData)
-- | Creates a new 'IOGenM'.
--
-- @since 1.2.0
newIOGenM :: MonadIO m => g -> m (IOGenM g)
newIOGenM = fmap IOGenM . liftIO . newIORef
instance (RandomGen g, MonadIO m) => StatefulGen (IOGenM g) m where
uniformWord32R r = applyIOGen (genWord32R r)
{-# INLINE uniformWord32R #-}
uniformWord64R r = applyIOGen (genWord64R r)
{-# INLINE uniformWord64R #-}
uniformWord8 = applyIOGen genWord8
{-# INLINE uniformWord8 #-}
uniformWord16 = applyIOGen genWord16
{-# INLINE uniformWord16 #-}
uniformWord32 = applyIOGen genWord32
{-# INLINE uniformWord32 #-}
uniformWord64 = applyIOGen genWord64
{-# INLINE uniformWord64 #-}
uniformShortByteString n = applyIOGen (genShortByteString n)
instance (RandomGen g, MonadIO m) => FrozenGen (IOGen g) m where
type MutableGen (IOGen g) m = IOGenM g
freezeGen = fmap IOGen . liftIO . readIORef . unIOGenM
thawGen (IOGen g) = newIOGenM g
-- | Applies a pure operation to the wrapped pseudo-random number generator.
--
-- ====__Examples__
--
-- >>> import System.Random.Stateful
-- >>> let pureGen = mkStdGen 137
-- >>> g <- newIOGenM pureGen
-- >>> applyIOGen random g :: IO Int
-- 7879794327570578227
--
-- @since 1.2.0
applyIOGen :: MonadIO m => (g -> (a, g)) -> IOGenM g -> m a
applyIOGen f (IOGenM ref) = liftIO $ do
g <- readIORef ref
case f g of
(!a, !g') -> a <$ writeIORef ref g'
{-# INLINE applyIOGen #-}
-- | Wraps an 'STRef' that holds a pure pseudo-random number generator.
--
-- * 'STGenM' is safe in the presence of exceptions, but not concurrency.
-- * 'STGenM' is slower than 'StateGenM' due to the extra pointer indirection.
--
-- @since 1.2.0
newtype STGenM g s = STGenM { unSTGenM :: STRef s g }
-- | Frozen version of mutable `STGenM` generator
--
-- @since 1.2.0
newtype STGen g = STGen { unSTGen :: g }
deriving (Eq, Ord, Show, RandomGen, Storable, NFData)
-- | Creates a new 'STGenM'.
--
-- @since 1.2.0
newSTGenM :: g -> ST s (STGenM g s)
newSTGenM = fmap STGenM . newSTRef
instance RandomGen g => StatefulGen (STGenM g s) (ST s) where
uniformWord32R r = applySTGen (genWord32R r)
{-# INLINE uniformWord32R #-}
uniformWord64R r = applySTGen (genWord64R r)
{-# INLINE uniformWord64R #-}
uniformWord8 = applySTGen genWord8
{-# INLINE uniformWord8 #-}
uniformWord16 = applySTGen genWord16
{-# INLINE uniformWord16 #-}
uniformWord32 = applySTGen genWord32
{-# INLINE uniformWord32 #-}
uniformWord64 = applySTGen genWord64
{-# INLINE uniformWord64 #-}
uniformShortByteString n = applySTGen (genShortByteString n)
instance RandomGen g => FrozenGen (STGen g) (ST s) where
type MutableGen (STGen g) (ST s) = STGenM g s
freezeGen = fmap STGen . readSTRef . unSTGenM
thawGen (STGen g) = newSTGenM g
-- | Applies a pure operation to the wrapped pseudo-random number generator.
--
-- ====__Examples__
--
-- >>> import System.Random.Stateful
-- >>> let pureGen = mkStdGen 137
-- >>> (runSTGen pureGen (\g -> applySTGen random g)) :: (Int, StdGen)
-- (7879794327570578227,StdGen {unStdGen = SMGen 11285859549637045894 7641485672361121627})
--
-- @since 1.2.0
applySTGen :: (g -> (a, g)) -> STGenM g s -> ST s a
applySTGen f (STGenM ref) = do
g <- readSTRef ref
case f g of
(!a, !g') -> a <$ writeSTRef ref g'
{-# INLINE applySTGen #-}
-- | Runs a monadic generating action in the `ST` monad using a pure
-- pseudo-random number generator.
--
-- ====__Examples__
--
-- >>> import System.Random.Stateful
-- >>> let pureGen = mkStdGen 137
-- >>> (runSTGen pureGen (\g -> applySTGen random g)) :: (Int, StdGen)
-- (7879794327570578227,StdGen {unStdGen = SMGen 11285859549637045894 7641485672361121627})
--
-- @since 1.2.0
runSTGen :: RandomGen g => g -> (forall s . STGenM g s -> ST s a) -> (a, g)
runSTGen g action = unSTGen <$> runST (withMutableGen (STGen g) action)
-- | Runs a monadic generating action in the `ST` monad using a pure
-- pseudo-random number generator. Returns only the resulting pseudo-random
-- value.
--
-- ====__Examples__
--
-- >>> import System.Random.Stateful
-- >>> let pureGen = mkStdGen 137
-- >>> (runSTGen_ pureGen (\g -> applySTGen random g)) :: Int
-- 7879794327570578227
--
-- @since 1.2.0
runSTGen_ :: RandomGen g => g -> (forall s . STGenM g s -> ST s a) -> a
runSTGen_ g action = fst $ runSTGen g action
-- | Wraps a 'TVar' that holds a pure pseudo-random number generator.
--
-- @since 1.2.1
newtype TGenM g = TGenM { unTGenM :: TVar g }
-- | Frozen version of mutable `TGenM` generator
--
-- @since 1.2.1
newtype TGen g = TGen { unTGen :: g }
deriving (Eq, Ord, Show, RandomGen, Storable, NFData)
-- | Creates a new 'TGenM' in `STM`.
--
-- @since 1.2.1
newTGenM :: g -> STM (TGenM g)
newTGenM = fmap TGenM . newTVar
-- | Creates a new 'TGenM' in `IO`.
--
-- @since 1.2.1
newTGenMIO :: MonadIO m => g -> m (TGenM g)
newTGenMIO g = liftIO (TGenM <$> newTVarIO g)
-- | @since 1.2.1
instance RandomGen g => StatefulGen (TGenM g) STM where
uniformWord32R r = applyTGen (genWord32R r)
{-# INLINE uniformWord32R #-}
uniformWord64R r = applyTGen (genWord64R r)
{-# INLINE uniformWord64R #-}
uniformWord8 = applyTGen genWord8
{-# INLINE uniformWord8 #-}
uniformWord16 = applyTGen genWord16
{-# INLINE uniformWord16 #-}
uniformWord32 = applyTGen genWord32
{-# INLINE uniformWord32 #-}
uniformWord64 = applyTGen genWord64
{-# INLINE uniformWord64 #-}
uniformShortByteString n = applyTGen (genShortByteString n)
-- | @since 1.2.1
instance RandomGen g => FrozenGen (TGen g) STM where
type MutableGen (TGen g) STM = TGenM g
freezeGen = fmap TGen . readTVar . unTGenM
thawGen (TGen g) = newTGenM g
-- | Applies a pure operation to the wrapped pseudo-random number generator.
--
-- ====__Examples__
--
-- >>> import Control.Concurrent.STM
-- >>> import System.Random.Stateful
-- >>> let pureGen = mkStdGen 137
-- >>> stmGen <- newTGenMIO pureGen
-- >>> atomically $ applyTGen uniform stmGen :: IO Int
-- 7879794327570578227
--
-- @since 1.2.1
applyTGen :: (g -> (a, g)) -> TGenM g -> STM a
applyTGen f (TGenM tvar) = do
g <- readTVar tvar
case f g of
(a, !g') -> a <$ writeTVar tvar g'
{-# INLINE applyTGen #-}
-- $uniform
--
-- This library provides two type classes to generate pseudo-random values:
--
-- * 'UniformRange' is used to generate a value of a type uniformly within a
-- range.
-- * 'Uniform' is used to generate a value of a type uniformly over all
-- possible values of that type.
--
-- Types may have instances for both or just one of 'UniformRange' and
-- 'Uniform'. A few examples illustrate this:
--
-- * 'Int', 'Data.Word.Word16' and 'Bool' are instances of both 'UniformRange' and
-- 'Uniform'.
-- * 'Integer', 'Float' and 'Double' each have an instance for 'UniformRange'
-- but no 'Uniform' instance.
-- * A hypothetical type @Radian@ representing angles by taking values in the
-- range @[0, 2π)@ has a trivial 'Uniform' instance, but no 'UniformRange'
-- instance: the problem is that two given @Radian@ values always span /two/
-- ranges, one clockwise and one anti-clockwise.
-- * It is trivial to construct a @Uniform (a, b)@ instance given
-- @Uniform a@ and @Uniform b@ (and this library provides this tuple
-- instance).
-- * On the other hand, there is no correct way to construct a
-- @UniformRange (a, b)@ instance based on just @UniformRange a@ and
-- @UniformRange b@.
-------------------------------------------------------------------------------
-- Notes
-------------------------------------------------------------------------------
-- $floating
--
-- The 'UniformRange' instances for 'Float' and 'Double' use the following
-- procedure to generate a random value in a range for @uniformRM (a, b) g@:
--
-- If \(a = b\), return \(a\). Otherwise:
--
-- 1. Generate \(x\) uniformly such that \(0 \leq x \leq 1\).
--
-- The method by which \(x\) is sampled does not cover all representable
-- floating point numbers in the unit interval. The method never generates
-- denormal floating point numbers, for example.
--
-- 2. Return \(x \cdot a + (1 - x) \cdot b\).
--
-- Due to rounding errors, floating point operations are neither
-- associative nor distributive the way the corresponding operations on
-- real numbers are. Additionally, floating point numbers admit special
-- values @NaN@ as well as negative and positive infinity.
--
-- For pathological values, step 2 can yield surprising results.
--
-- * The result may be greater than @max a b@.
--
-- >>> :{
-- let (a, b, x) = (-2.13238e-29, -2.1323799e-29, 0.27736077)
-- result = x * a + (1 - x) * b :: Float
-- in (result, result > max a b)
-- :}
-- (-2.1323797e-29,True)
--
-- * The result may be smaller than @min a b@.
--
-- >>> :{
-- let (a, b, x) = (-1.9087862, -1.908786, 0.4228573)
-- result = x * a + (1 - x) * b :: Float
-- in (result, result < min a b)
-- :}
-- (-1.9087863,True)
--
-- What happens when @NaN@ or @Infinity@ are given to 'uniformRM'? We first
-- define them as constants:
--
-- >>> nan = read "NaN" :: Float
-- >>> inf = read "Infinity" :: Float
--
-- * If at least one of \(a\) or \(b\) is @NaN@, the result is @NaN@.
--
-- >>> let (a, b, x) = (nan, 1, 0.5) in x * a + (1 - x) * b
-- NaN
-- >>> let (a, b, x) = (-1, nan, 0.5) in x * a + (1 - x) * b
-- NaN
--
-- * If \(a\) is @-Infinity@ and \(b\) is @Infinity@, the result is @NaN@.
--
-- >>> let (a, b, x) = (-inf, inf, 0.5) in x * a + (1 - x) * b
-- NaN
--
-- * Otherwise, if \(a\) is @Infinity@ or @-Infinity@, the result is \(a\).
--
-- >>> let (a, b, x) = (inf, 1, 0.5) in x * a + (1 - x) * b
-- Infinity
-- >>> let (a, b, x) = (-inf, 1, 0.5) in x * a + (1 - x) * b
-- -Infinity
--
-- * Otherwise, if \(b\) is @Infinity@ or @-Infinity@, the result is \(b\).
--
-- >>> let (a, b, x) = (1, inf, 0.5) in x * a + (1 - x) * b
-- Infinity
-- >>> let (a, b, x) = (1, -inf, 0.5) in x * a + (1 - x) * b
-- -Infinity
--
-- Note that the [GCC 10.1.0 C++ standard library](https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/include/bits/random.h;h=19307fbc3ca401976ef6823e8fda893e4a263751;hb=63fa67847628e5f358e7e2e7edb8314f0ee31f30#l1859),
-- the [Java 10 standard library](https://docs.oracle.com/javase/10/docs/api/java/util/Random.html#doubles%28double,double%29)
-- and [CPython 3.8](https://github.com/python/cpython/blob/3.8/Lib/random.py#L417)
-- use the same procedure to generate floating point values in a range.
--
-- $implementmonadrandom
--
-- Typically, a monadic pseudo-random number generator has facilities to save
-- and restore its internal state in addition to generating pseudo-random numbers.
--
-- Here is an example instance for the monadic pseudo-random number generator
-- from the @mwc-random@ package:
--
-- > instance (s ~ PrimState m, PrimMonad m) => StatefulGen (MWC.Gen s) m where
-- > uniformWord8 = MWC.uniform
-- > uniformWord16 = MWC.uniform
-- > uniformWord32 = MWC.uniform
-- > uniformWord64 = MWC.uniform
-- > uniformShortByteString n g = unsafeSTToPrim (genShortByteStringST n (MWC.uniform g))
--
-- > instance PrimMonad m => FrozenGen MWC.Seed m where
-- > type MutableGen MWC.Seed m = MWC.Gen (PrimState m)
-- > thawGen = MWC.restore
-- > freezeGen = MWC.save
--
-- === @FrozenGen@
--
-- `FrozenGen` gives us ability to use any stateful pseudo-random number generator in its
-- immutable form, if one exists that is. This concept is commonly known as a seed, which
-- allows us to save and restore the actual mutable state of a pseudo-random number
-- generator. The biggest benefit that can be drawn from a polymorphic access to a
-- stateful pseudo-random number generator in a frozen form is the ability to serialize,
-- deserialize and possibly even use the stateful generator in a pure setting without
-- knowing the actual type of a generator ahead of time. For example we can write a
-- function that accepts a frozen state of some pseudo-random number generator and
-- produces a short list with random even integers.
--
-- >>> import Data.Int (Int8)
-- >>> :{
-- myCustomRandomList :: FrozenGen f m => f -> m [Int8]
-- myCustomRandomList f =
-- withMutableGen_ f $ \gen -> do
-- len <- uniformRM (5, 10) gen
-- replicateM len $ do
-- x <- uniformM gen
-- pure $ if even x then x else x + 1
-- :}
--
-- and later we can apply it to a frozen version of a stateful generator, such as `STGen`:
--
-- >>> print $ runST $ myCustomRandomList (STGen (mkStdGen 217))
-- [-50,-2,4,-8,-58,-40,24,-32,-110,24]
--
-- or a @Seed@ from @mwc-random@:
--
-- >>> import Data.Vector.Primitive as P
-- >>> print $ runST $ myCustomRandomList (MWC.toSeed (P.fromList [1,2,3]))
-- [24,40,10,40,-8,48,-78,70,-12]
--
-- Alternatively, instead of discarding the final state of the generator, as it happens
-- above, we could have used `withMutableGen`, which together with the result would give
-- us back its frozen form. This would allow us to store the end state of our generator
-- somewhere for the later reuse.
--
--
-- $references
--
-- 1. Guy L. Steele, Jr., Doug Lea, and Christine H. Flood. 2014. Fast
-- splittable pseudorandom number generators. In Proceedings of the 2014 ACM
-- International Conference on Object Oriented Programming Systems Languages &
-- Applications (OOPSLA '14). ACM, New York, NY, USA, 453-472. DOI:
-- <https://doi.org/10.1145/2660193.2660195>
-- $setup
-- >>> import Control.Monad.Primitive
-- >>> import qualified System.Random.MWC as MWC
-- >>> writeIORef theStdGen $ mkStdGen 2021
--
-- >>> :set -XFlexibleContexts
-- >>> :set -XFlexibleInstances
-- >>> :set -XMultiParamTypeClasses
-- >>> :set -XTypeFamilies
-- >>> :set -XUndecidableInstances
--
-- >>> :{
-- instance (s ~ PrimState m, PrimMonad m) => StatefulGen (MWC.Gen s) m where
-- uniformWord8 = MWC.uniform
-- uniformWord16 = MWC.uniform
-- uniformWord32 = MWC.uniform
-- uniformWord64 = MWC.uniform
-- uniformShortByteString n g = unsafeSTToPrim (genShortByteStringST n (MWC.uniform g))
-- instance PrimMonad m => FrozenGen MWC.Seed m where
-- type MutableGen MWC.Seed m = MWC.Gen (PrimState m)
-- thawGen = MWC.restore
-- freezeGen = MWC.save
-- :}
--