Compile time function execution...
Ary Manzana
ary at esperanto.org.ar
Thu Feb 15 10:39:09 PST 2007
Walter Bright escribió:
> ... 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 really great, Walter! Congratulations!
I'm always thinking that D is focused on great runtime performance while
having great expresiveness, which is awsome. I can't believe computers
have evolved that much... and still we have to wait 10 o 20 seconds for
a program to load :-(
A question: is there anyway the compiler can tell the user if a certain
function can be executed at compile time? Those six rules may be hard to
memorize and while coding sensitive code it would be great to ask the
compiler "Is the function I'm writing can be executed at compile time?".
Otherwise it's just a guess.
More information about the Digitalmars-d
mailing list