[OpenSCAD] Openscad Indirect Functions

Carsten Arnholm arnholm at arnholm.org
Mon Oct 10 17:23:53 EDT 2016

On 10. okt. 2016 19:13, otto wrote:
> On Mon, 10 Oct 2016 10:44:13 +0100
> nop head <nop.head at gmail.com> wrote:
>> So @xsq becomes both a name mangled function and a variable holding
>> its name? That seems like a bit of a kludge to me.
> Well its like this, you can pass a function with the name of the
> function in quotes.
> function div3(x)=x/3;
> vec = [1,2,3];
> function map(func,vec) = [for (i=vec) @func(i)];
> echo(map("div3",vec));
> And it works:
> Compiling design (CSG Tree generation)...
> ECHO: [0.333333, 0.666667, 1]

Sometimes I wonder why OpenSCAD reinvents standard language features of 
existing languages... below are some thoughts intended as inspiration. 
Your example code is applied to AngelScript, a language I use for 3d 

funcdef double FUNC(double x);
double div3(double x) { return x/3; }
void map(FUNC @func, double[] @vec)
    { for(uint i=0; i<vec.size(); i++) { vec[i]=func(vec[i]); }  }

void main()
    double[] vec = { 1,2,3 };
    for(uint i=0; i<vec.size(); i++) print(vec[i]+' ');

output is the expected:
    0.333333 0.666667 1

First, a function signature 'FUNC' is defined, i.e. one taking and 
returning a double. Second, an actual function 'div3' with a signature 
compatible with FUNC is defined. Third, the 'map' function where the 
'func' parameter is passed 'by handle' using @ resembles your code 
(alternate syntax "FUNC@ func" also ok). The array 'vec' also passed 'by 
handle' so the caller sees the modified 'vec' after calling 'map'

If I had tried to call map using another function, e.g.
double divn(double x, int n) { return x/n; }
it would generate an error because 'divn' is incompatible with the FUNC 
signature. It is not clear from your example what happens if you did a 
similar mistake.

Just take this comment as food for thought & inspiration.

Carsten Arnholm

More information about the Discuss mailing list