[mercury-users] Converting time_t to int using common library?

Julian Fondren ayrnieu at gmail.com
Wed Feb 14 20:11:51 AEDT 2007


On 2/13/07, Peter Schachte <schachte at csse.unimelb.edu.au> wrote:
> One problem with this is that if you call it twice in rapid succession, it
> will
> probably give you the same random supply.  It would probably be better for
> subsequent calls to this to us some function (e.g., xor) of the time and the
> previously generated seed.

Ah, thanks: this problem is a good argument for extending random.m (another:
that a mature random.m can use platform-appropriate /dev/Xrandom and
external sources of entropy) instead of changing time.m to support this
particular C idiom.

However, xor doesn't work very well for this: given a cached seed S, the second
of two functionally simultaneous calls to random.init will return S.  I think
+ would do better.

Cheers,
Julian


% -- for example, a random.init/3 that gets random bits from /dev/urandom
random.init(rs(RS), !IO) :-
    io.open_binary_input("/dev/urandom", Res, !IO),
    (
        Res = ok(F),
        random.random_bytes(F, int.bits_per_int // 8, 0, RS, !IO),
        io.close_binary_input(F, !IO)
    ;
        Res = error(_),
        error("please make me handle errors intelligently :-)")
    ).

:- pred random.random_bytes(io.binary_input_stream,
    int, int, int, io.io, io.io).
:- mode random.random_bytes(in, in, di, uo, di, uo) is det.
random.random_bytes(F, N, !RS, !IO) :-
    (
        N =< 0
    ->
        true
    ;
        io.read_byte(F, Res, !IO),
        (
            Res = ok(B),
            !:RS = (!.RS << 8) \/ B,
            random.random_bytes(F, N - 1, !RS, !IO)
        ;
            Res = eof,
            error("this really shouldn't be possible.")
        ;
            Res = error(_),
            error("please make me handle errors intelligently :-)")
        )
    ).
--------------------------------------------------------------------------
mercury-users mailing list
Post messages to:       mercury-users at csse.unimelb.edu.au
Administrative Queries: owner-mercury-users at csse.unimelb.edu.au
Subscriptions:          mercury-users-request at csse.unimelb.edu.au
--------------------------------------------------------------------------



More information about the users mailing list