Skip to content

Commit

Permalink
Add overwriteGen to FrozenGen
Browse files Browse the repository at this point in the history
  • Loading branch information
lehins committed Nov 12, 2023
1 parent c324ab0 commit 66f0f10
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 1.3.0

* Add `modifyGen` to the `FrozenGen` type class
* Add `modifyGen` and `overwriteGen` to the `FrozenGen` type class
* Add `splitFrozenM` and `splitMutableM`
* Switch `randomM` and `randomRM` to use `FrozenGen` instead of `RandomGenM`
* Deprecate `RandomGenM` in favor of a more powerful `FrozenGen`
Expand Down
7 changes: 7 additions & 0 deletions src/System/Random/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,11 @@ class StatefulGen (MutableGen f m) m => FrozenGen f m where
-- @since 1.3.0
modifyGen :: MutableGen f m -> (f -> (a, f)) -> m a

-- | Overwrite the mutable generator with the supplied frozen one
--
-- @since 1.3.0
overwriteGen :: MutableGen f m -> f -> m ()
overwriteGen mg fg = modifyGen mg (const ((), fg))

-- | Splits a pseudo-random number generator into two. Overwrites the mutable
-- wrapper with one of the resulting generators and returns the other.
Expand Down Expand Up @@ -479,6 +484,8 @@ instance (RandomGen g, MonadState g m) => FrozenGen (StateGen g) m where
thawGen (StateGen g) = StateGenM <$ put g
modifyGen _ f = state (coerce f)
{-# INLINE modifyGen #-}
overwriteGen _ f = put (coerce f)
{-# INLINE overwriteGen #-}

-- | Splits a pseudo-random number generator into two. Updates the state with
-- one of the resulting generators and returns the other.
Expand Down
6 changes: 6 additions & 0 deletions src/System/Random/Stateful.hs
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,8 @@ instance (RandomGen g, MonadIO m) => FrozenGen (IOGen g) m where
g' `seq` writeIORef ref g'
pure a
{-# INLINE modifyGen #-}
overwriteGen (IOGenM ref) = liftIO . writeIORef ref . unIOGen
{-# INLINE overwriteGen #-}

-- | Applies a pure operation to the wrapped pseudo-random number generator.
--
Expand Down Expand Up @@ -538,6 +540,8 @@ instance RandomGen g => FrozenGen (STGen g) (ST s) where
g' `seq` writeSTRef ref g'
pure a
{-# INLINE modifyGen #-}
overwriteGen (STGenM ref) = writeSTRef ref . unSTGen
{-# INLINE overwriteGen #-}


-- | Applies a pure operation to the wrapped pseudo-random number generator.
Expand Down Expand Up @@ -639,6 +643,8 @@ instance RandomGen g => FrozenGen (TGen g) STM where
g' `seq` writeTVar ref g'
pure a
{-# INLINE modifyGen #-}
overwriteGen (TGenM ref) = writeTVar ref . unTGen
{-# INLINE overwriteGen #-}


-- | Applies a pure operation to the wrapped pseudo-random number generator.
Expand Down

0 comments on commit 66f0f10

Please sign in to comment.