www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - std.algorithm.map - function by reference

reply "kuba" <kuba456 gmail.com> writes:
Hi there,
I was wondering if std.algorithm.map can take functions with 
parameters passed by reference? The main point here is to avoid 
unnecessary copies by perhaps I'm using the wrong tool for the 
job.

Thank you,
kuba

////////////////////////

import std.algorithm, std.math;
import std.stdio;

double ksqrCpy( double _in){
     return sqrt(_in);
}

void ksqrRef(ref double _in){
     _in = sqrt(_in);
}

void main() {
     double[] arr1 = [ 1, 2, 3, 4 ];
     map!ksqrRef (arr1);
     writeln("a ref : ", arr1);
     auto byCpy= map!ksqrCpy (arr1);
     writeln("a copy: ", byCpy);
}
Jun 24 2014
next sibling parent Justin Whear <justin economicmodeling.com> writes:
On Tue, 24 Jun 2014 21:46:15 +0000, kuba wrote:

 Hi there,
 I was wondering if std.algorithm.map can take functions with 
 parameters passed by reference? The main point here is to avoid 
 unnecessary copies by perhaps I'm using the wrong tool for the 
 job.
No, `map` is a _projection_ function and is not intended to perform modification in place. There has been discussion of an `each` function which would act as a sink and which could potentially pass by reference.
Jun 24 2014
prev sibling parent "Adam D. Ruppe" <destructionator gmail.com> writes:
On Tuesday, 24 June 2014 at 21:46:16 UTC, kuba wrote:
 The main point here is to avoid unnecessary copies
You should make sure this actually matters - passing doubles by ref for example is probably slower than just passing a regular double.
Jun 24 2014