On 05/16/2011 01:08 PM, dmerrio wrote:
I am parsing some formulas from a spreadsheet file. To duplicate
the behavior of the spreadsheet functions, I am having to create a
lot of boiler plate code that maps from the spreadsheet functions
to the built-in functions. Mixin would seem to allow me to
automate the boiler-plate creation, but i am not utilizing it
correctly. What is the correct to call Mixin in this situation, or
is their a better way to create the boiler-plate code?

For background, i am new to D. D is my second language with my
primary experience being a script kiddie in Excel VBA, so take it
slow, please.



import main; //class definition of rng
import std.math; //trig functions
import std.conv; //to!double
import std.string; //toupper

double transFunc(alias transedentalFunc)(rng aRng){
        try{return(transedentalFunc(aRng.getCellValue().coerce!
(double)));} //cellValue stored as a Variant
        catch{return(transedentalFunc(to!double(aRng.getCellValue
().coerce!(string))));} //replicate spreadsheet behavior and
convert to a number
}

//Example 1 of boilerplate code
double SIN(double aReal){return(sin(aReal));}
double SIN(string aStr){return(sin(to!double(aStr)));}
double SIN(rng aRng){return(transFunc!(sin)(aRng));}

//Example 2 of boilerplate code
double COS(double aReal){return(cos(aReal));}
double COS(string aStr){return(cos(to!double(aStr)));}
double COS(rng aRng){return(transFunc!(cos)(aRng));}

string[] funcs = ["tan"];
void createFuncs(){
        foreach(func; funcs){
                mixin("double " ~ toupper(func) ~ "(double aReal)
{return(" ~ func ~ "(aReal));}");
        }
}

calling mixin a compile time has the following error...

Error   1       Error: variable func cannot be read at compile time
        C:\D\SVNProjects\trunk\xcellD\xcell1\trig.d     22


thanks for your help

This works:

//import main; //class definition of rng
import std.math; //trig functions
import std.conv; //to!double
import std.string; //toupper
import std.stdio;

void main()
{
    mixin(createFunc!("sin"));
    mixin(createFunc!("cos"));
    mixin(createFunc!("tan"));
    writeln(SIN(0)); // 0
    writeln(COS(0)); // 1
    writeln(TAN(0)); // 0
    return;
}
template createFunc(string func){
    const char[] createFunc = "double " ~ toupper(func) ~ "(double aReal)
        {return(" ~ func ~ "(aReal));}";
}

Stole it from http://www.digitalmars.com/d/2.0/mixin.html

I don't think there's a way to use an array of strings, since (as pointed out by others and your error message) that mixins are done compile-time and foreach are done (mostly) at run-time.

Reply via email to