www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - fill array using a lambda function

reply "dominic jones" <dominic.jones gmx.co.uk> writes:
Hello,

I want to fill an array with random numbers without resorting to 
loops, i.e. by doing something like the following, if it were 
possible:

   fill!(function double(){ return uniform(0.0, 1.0);})(x[]);

Is there a simple way of doing this?

Thank you,
Dominic Jones

P.S. I am aware of the function uniformDistribution, but it makes 
the sum of the elements equal to 1, which I don't want.
Oct 10 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
dominic jones:

 I want to fill an array with random numbers without resorting 
 to loops, i.e. by doing something like the following, if it 
 were possible:

   fill!(function double(){ return uniform(0.0, 1.0);})(x[]);

 Is there a simple way of doing this?
Generally it's a good idea to use only pure functions inside the higher order functions of Phobos. using impure functions like uniforms could lead to bugs or performance problems. This is a way to do it (untested): x.copy(x.length.iota.map!(_ => uniform(0.0, 1.0)); Bye, bearophile
Oct 10 2013
parent reply "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
On 2013-10-10, 16:04, bearophile wrote:

 dominic jones:

 I want to fill an array with random numbers without resorting to loops,  
 i.e. by doing something like the following, if it were possible:

   fill!(function double(){ return uniform(0.0, 1.0);})(x[]);

 Is there a simple way of doing this?
Generally it's a good idea to use only pure functions inside the higher order functions of Phobos. using impure functions like uniforms could lead to bugs or performance problems. This is a way to do it (untested): x.copy(x.length.iota.map!(_ => uniform(0.0, 1.0));
You've got the order wrong - copy takes first the source, then the target. Also, is it faster to use .length.iota than simply mapping on x? My solution: x.map!(_=>uniform(0.0, 1.0)).copy(x); -- Simen
Oct 10 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
Simen Kjaeraas:

 You've got the order wrong - copy takes first the source, then 
 the target.
I'd like it to be (re)named "copyTo" to avoid me such common mistake. Bye, bearophile
Oct 10 2013