qri-io / starlib

qri's standard library for starlark
MIT License
114 stars 29 forks source link

Implement a `random` module #65

Open rohansingh opened 3 years ago

rohansingh commented 3 years ago

What feature or capability would you like?

It would be nice to be able to generate random numbers.

Do you have a proposed solution?

Implement a random module that uses math/rand under the hood.

Have you considered any alternative solutions or workarounds?

From @betterengineering:

def random(seed):
    """
    Returns a random number and the new seed value.

    Starlark is meant to be deterministic, so anything that made the language non-deterministic (such as random number
    generators) was removed. This is a Python implementation of a linear congruential generator I found here:
    http://www.cs.wm.edu/~va/software/park/park.html
    """
    modulus = 2147483648
    multiplier = 48271

    q = modulus / multiplier
    r = modulus % multiplier
    t = multiplier * (seed % q) - r * (seed / q);

    if t > 0:
        seed = t
    else:
        seed = t + modulus

    return float(seed / modulus), seed
b5 commented 3 years ago

I agree having a random module would be nice. Not everyone is building with pseudo-determinism as a hard constraint. That said we should include a few changes to make access to the random package opt-in by default. I think adding a random package merits exporting a second top-level loader (or at least a configurable top-level loader) that determines weather the random package is available.

The second thing I'd expect from such a package would be an explicit set of controls within the go runtime to wrap and control any seed values within the starlark runtime

edit: hit submit too soon!