http://d.puremagic.com/issues/show_bug.cgi?id=5249
Summary: Strongly pure random generator Product: D Version: D2 Platform: All OS/Version: All Status: NEW Severity: enhancement Priority: P2 Component: Phobos AssignedTo: nob...@puremagic.com ReportedBy: bearophile_h...@eml.cc --- Comment #0 from bearophile_h...@eml.cc 2010-11-21 15:47:51 PST --- As pure functions become more and more common in D2 programs, I'd like to generate some random values inside them too. So I suggest to add to the std.random module a strongly pure function that keeps no state and generates random values. This code shows that it's doable (but it's just for demonstration, because this pseudo random generator is too much weak): import std.stdio: writeln; immutable struct rndPair { double seed, rnd; } // strongly pure // Probably with DMD 2.050 a std.typecons.Tuple can't // be used as return value here pure nothrow rndPair nextRandom(const double seed, const double max) { enum int IA = 3_877, IC = 29_573, IM = 139_968; immutable double new_seed = (seed * IA + IC) % IM; return rndPair(new_seed, max * (new_seed * (1.0 / IM))); } // strongly pure pure double[] foo(const int n, const double firstSeed=42) { double seed = firstSeed; auto res = new double[n]; foreach (ref r; res) { auto seed_rnd = nextRandom(seed, 1.0); r = seed_rnd.rnd; seed = seed_rnd.seed; } return res; } void main() { writeln(foo(5)); // Output: // [0.37465, 0.729024, 0.636467, 0.793481, 0.538545] } If you want two different strongly pure functions may be added, one good enough generator and one better generator. Once some unpacking syntax for tuples is present in DMD the foo() may become more elegant, similar to (this uses what Andrei calls the 'banana syntax', but other syntaxes are possible): pure double[] foo(const int n, const double firstSeed=42) { double seed = firstSeed; auto res = new double[n]; foreach (ref r; res) (|r, seed|) = nextRandom(seed, 1.0); return res; } See also bug 5124 -- Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: -------