generate an array of 100 uniform distributed numbers
Justin Whear via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jan 22 11:36:43 PST 2015
On Thu, 22 Jan 2015 19:26:44 +0000, ddos wrote:
> hi guys, firstly this has no direct application, i'm just playing around
> and learning
>
> i want to create 100 uniform distributed numbers and print them my first
> attempt, just written by intuition:
> [0 .. 100].map!(v => uniform(0.0, 1.0).writeln);
>
> i found out i can't write [0 .. 100] to define a simple number range,
> but is there a function to do so?
The iota function from std.range:
iota(0, 100).map!(...)
>
> second attempt, replacing the range with an simple array [0,1,2].map!(v
> => uniform(0.0,1.0).writeln);
> this does compile and run, but doesn't print anything, just an empty
> string, why is that?
Two issues:
1) The function supplied to map should be a projection function, e.g. it
takes a value and returns a value. Your lambda returns void (the result
of writeln).
2) map is lazy--it doesn't do any work until something consumes it. This
is awesome for many reasons (e.g. you can process infinite ranges).
Nothing in your code is causing the result of map to be consumed, so it
does no work.
> finally i got it working with this:
> auto t = [0,1,2].map!(v => uniform(0.0,1.0));
> writeln(t);
This works because writeln eagerly consumes the result of map, causing
the work to actually be done. If you like, you can tack the writeln to
the end of the pipeline:
auto t = [0,1,2].map!(v => uniform(0.0,1.0)).writeln;
More information about the Digitalmars-d-learn
mailing list