www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to make a function table?

reply mnar53 <maurizionardo hotmail.it> writes:
Absolutely a newbie to D. This code mimics c, but unfortunately 
does not work:


import std.typecons;
import std.math;

alias double function(double) UNARY;


UNARY[] FCNS = [sin, cos, tan];


double[][] MAP (int idx, double[][] args) nothrow {
     UNARY f = FCNS[idx];
     foreach(i; 0 .. args.length)
         foreach(j; 0 .. args[i].length)
             args[i][j] = f (args[i][j]);
     return args;
}


what's wrong with it?
Feb 15 2019
parent reply Alex <sascha.orlov gmail.com> writes:
On Saturday, 16 February 2019 at 05:06:55 UTC, mnar53 wrote:
 Absolutely a newbie to D. This code mimics c, but unfortunately 
 does not work:


 import std.typecons;
 import std.math;

 alias double function(double) UNARY;


 UNARY[] FCNS = [sin, cos, tan];


 double[][] MAP (int idx, double[][] args) nothrow {
     UNARY f = FCNS[idx];
     foreach(i; 0 .. args.length)
         foreach(j; 0 .. args[i].length)
             args[i][j] = f (args[i][j]);
     return args;
 }


 what's wrong with it?
I assume, this would do its job: ´´´ import std.typecons; import std.math; alias UNARY = double function(double); UNARY[] FCNS = [&sin, &cos, &tan]; double[][] MAP (size_t idx, double[][] args) { UNARY f = FCNS[idx]; foreach(i; 0 .. args.length) foreach(j; 0 .. args[i].length) args[i][j] = f (args[i][j]); return args; } void main(){ double[][] args; args.length = 3; foreach(ref el; args) el.length = 3; import std.random : uniform01, dice; foreach(l; args) foreach(ref el; l) el = uniform01; import std.range : iota; args = MAP(dice(FCNS.length.iota), args); import std.stdio : writeln; writeln(args); } ´´´
Feb 15 2019
parent mnar53 <maurizionardo hotmail.it> writes:
On Saturday, 16 February 2019 at 06:29:28 UTC, Alex wrote:
 On Saturday, 16 February 2019 at 05:06:55 UTC, mnar53 wrote:
 [...]
I assume, this would do its job: ´´´ import std.typecons; import std.math; [...]
Yes, it works. Thx.
Feb 16 2019