Compile time function execution...
Bill Baxter
dnewsgroup at billbaxter.com
Thu Feb 15 17:14:43 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 doesn't seem to work either -- should it?
char[] UpToSpace(char[] x)
{
int i=0;
while (i<x.length && x[i] != ' ') {
i++;
}
return x[0..i];
}
void main()
{
const y = UpToSpace("first space was after first");
writefln(y);
}
It prints out the whole string rather than just "first".
If you change it to return 'i' it does correctly evaluate to 5.
If you change it to just 'return x[0..5];' it also works correctly.
--bb
More information about the Digitalmars-d
mailing list