Compile time function execution...

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Thu Feb 15 11:04:53 PST 2007


Walter Bright wrote:
> ... is now in DMD 1.006. For example:
> 
>> -------------------------------------------
>> import std.stdio;
>>
>> real sqrt(real x)
>> {
>>    real root = x / 2;
>>    for (int ntries = 0; ntries < 5; ntries++)
>>    {
>>        if (root * root - x == 0)
>>            break;
>>        root = (root + x / root) / 2;
>>    }
>>    return root;
>> }
>>
>> void main()
>> {
>>    static x = sqrt(10);   // woo-hoo! set to 3.16228 at compile time!
>>    writefln("%s, %s", x, sqrt(10));  // this sqrt(10) runs at run time
>> }
>> ------------------------------------------
> 
> This should obsolete using templates to compute values at compile time.

This is a development of epic proportions.

There is a need for a couple of ancillary features. Most importantly, a 
constant must be distinguishable from a variable. Consider the example 
of regex from our correspondence:

bool b = regexmatch(a, "\n$");

vs.

char[] pattern = argv[1];
bool b = regexmatch(a, pattern);

You'd want to dispatch regexmatch differently: the first match should be 
passed to compile-time code that at the end of the day yields:

bool b = (a[$-1] == '\n');

while the second should invoke the full-general dynamic pattern matching 
algorithm since a dynamic pattern is used.


Andrei



More information about the Digitalmars-d mailing list