Compile time function execution...
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Thu Feb 15 11:25:07 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.
Hmm... infinite loops are suddenly _really_ slow to compile ;) :
-----
// Slightly modified from example
import std.stdio;
real test(real x)
{
real root = x / 2;
for (int ntries = 0; ntries < 5 || true; ntries++) {
root = (root + x / root) / 2;
}
return root;
}
void main()
{
static x = test(10);
}
-----
(Also, this seems to consume huge amounts of memory)
And error checking could be improved as well: removing the parameter
from the call in above code gives
---
test.d(15): function test.test (real) does not match parameter types ()
test.d(15): Error: expected 1 arguments, not 0
dmd: interpret.c:96: Expression*
FuncDeclaration::interpret(Expressions*): Assertion `parameters &&
parameters->dim == dim' failed.
Aborted (core dumped)
---
It tells you what's wrong, but still trips an assert that seems to be
about the same error. However:
-----
real test()
{
return 0.0;
}
void main()
{
static x = test();
}
-----
Gives:
---
dmd: interpret.c:96: Expression*
FuncDeclaration::interpret(Expressions*): Assertion `parameters &&
parameters->dim == dim' failed.
Aborted (core dumped)
---
(the same assert is tripped)
So I don't know, maybe it's a different bug entirely. Or it tripped the
other clause of the assert. I don't feel like inspecting interpret.c to
find out what exactly the assert is checking and why it's false...
More information about the Digitalmars-d
mailing list