Thread overview
How to make a function table?
Feb 16, 2019
mnar53
Feb 16, 2019
Alex
Feb 16, 2019
mnar53
February 16, 2019
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?
February 16, 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);
}
´´´
February 16, 2019
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.