[Haskell-cafe] DeepSeq and random generators

Jonas Scholl anselm.scholl at tu-harburg.de
Tue Jul 18 09:40:16 UTC 2017


You cannot derive the instance because the type is opaque, i.e. the
constructors are not exported. However, there are multiple ways to write
the instance yourself: Looking at the code for StdGen, it seems like

    rnf stdgen = stdgen `seq` ()

would suffice as an implementation (StdGen only contains two strict
ints, so forcing it to WHNF is equivalent to HNF). However, this would
be incorrect if StdGen would ever change. Another idea would be to
generate something you can force (e.g. an Int) from the gen and force
that Int. This assumes that getting the next random number from a
generator would force all (relevant) parts of the old generator state.
So you would have something like this:

    rnf stdgen = case next stdgen of
        (i, _) -> rnf i

Depending on your application, you may want to wrap the StdGen in a
newtype to avoid an orphan instance.

On 07/18/2017 11:18 AM, Dennis Raddle wrote:
> I'm having trouble using Control.DeepSeq.force (necessary for parallel
> code) on a StdGen from System.Random. I don't know how to derive NFData.
> A standalone deriving statement, like this
> 
> deriving instance NFData StdGen 
> 
> gets me the error "the data constructors of StdGen are not all in scope..."
> 
> Is it actually possible to derive an NFData instance of StdGen, and how
> would I do that? Or if not possible, how can I work about this?
> 
> Note: I'm going to see if I can use tf-random in this application. Maybe
> it will be easier.
> 
> D
> 
> 
> 
> _______________________________________________
> Haskell-Cafe mailing list
> To (un)subscribe, modify options or view archives go to:
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
> Only members subscribed via the mailman list are allowed to post.
> 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 488 bytes
Desc: OpenPGP digital signature
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20170718/a7d7fd06/attachment.sig>


More information about the Haskell-Cafe mailing list