[m-users.] Random Number Generator

Julien Fischer jfischer at opturion.com
Mon Jul 31 22:33:27 AEST 2023


On Mon, 31 Jul 2023, Volker Wysk wrote:

> Am Montag, dem 31.07.2023 um 09:46 +1000 schrieb Mark Brown:

>> In C terms, this is akin to having access to a global resource (e,g,,
>> /dev/urandom), but having your code pass around the file handle with
>> which the process accesses it. You could avoid passing around the
>> handle by using a global static variable if you wanted.
>>
>> Similarly, in Mercury you could use a module-local mutable variable to
>> store the system_rng handle, once initialized.
>
> I'm using system_rng for creating a random seed only. It's the "M" variable
> of type io_urandom(P, S), the result of make_io_urandom, which I don't want
> to carry around.
>
> I've looked for info on mutable variables and found the modules thread.mvar,
> store and mutvar (which is undocumented). It's confusing. It uses impurity
> and I can't see how to make and initialize a handle to a mutable variable
> local to a module, such that nothing needs to be carried around. It looks to
> me like some use of promise_pure is needed - but would that be safe?

Mark is referring to module-local mutable variables as described in
section 10.6 of the reference manual. Have a look at what the
attach_to_io_state attribute does.

>>> Actually, that M argument is of type params and this is a dummy type (from
>>> the source code of random.sfc64):
>>>
>>> :- type params
>>>     --->    params.
>>>
>>> It's the same for random.sfc32, but not for random.sfc16. And the module
>>> random.sfc64 defines this:
>>>
>>> :- pred generate_uint64(uint64::out, ustate::di, ustate::uo) is det.
>>>
>>> That's looks like what I need, but there isn't such a member of the urandom
>>> type class, which I need to use when I want it to be attached to the IO
>>> state.
>>
>> Since you're digging into the implementation, you could look at the
>> source code of make_io_urandom to see what's going on. It wraps the
>> ustate, which is destructively updatable because it is unique (it's an
>> array), in a mutvar, which is destructively updatable because it is
>> attached to the I/O state.
>>
>> By "destructively updatable" I mean that there is some way for the
>> compiler to verify that such an update is safe. The two interfaces
>> provide two such options, though the actual update that is happening
>> is the same either way.
>
> Sorry, but this makes me even more confused. I think, I'll bite the bullet
> and pass around that dummy variable.

The dummy variable is necessary because otherwise you couldn't create
instances of the urandom type class.  Also, for some random number
generators, it is not a dummy variable (e.g. on some systems the
system_rng handle contains the file descriptor used to open /dev/urandom
etc.)

Julien.


More information about the users mailing list