How to make a function table?

Alex sascha.orlov at gmail.com
Sat Feb 16 06:29:28 UTC 2019


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);
}
´´´


More information about the Digitalmars-d-learn mailing list