Nesting in pure functions

Don nospam at nospam.com
Mon Apr 6 02:17:30 PDT 2009


bearophile wrote:
> This post was originally meant for digitalmars.D.learn, but maybe it can interest more people here.
> 
> Now that the D1/D2 zips have a better internal structure and don't require DMC anymore I am more free to use D2 more, so I have tried to understand how the optimization of pure functions works.
> 
> So I have written this toy program that computes:
> ((x*x)+(x*x)) + ((x*x)+(x*x))
> 
> 
> import std.c.stdio: printf;
> import std.conv: toInt;
> 
> pure int double_sqr(int x) {
>     int y, z;
>     void do_sqr() { y *= y; }
>     y = x;
>     do_sqr();
>     z += y;
>     y = x;
>     do_sqr();
>     z += y;
>     return z;
> }
> 
> void main(string[] args) {
>     int x = args.length == 2 ? toInt(args[1]) : 10;
>     int y = double_sqr(x) + double_sqr(x);
>     printf("4 * x * x = %d\n", y);
> }
> 

> double_sqr() is a pure function. do_sqr() isn't a pure function, but it has no side effects outside double_sqr(), so double_sqr() is globally pure still. But the compiler (dmd v2.027) doesn't accept it (notice the strange blank line in the middle):

There's some compiler bugs. Try:

     void do_sqr() pure { y *= y; }

and it compiles, but generates wrong code.
pure void do_sqr() doesn't compile. Nothrow behaves the same.
Compare with bugzilla 2694.

But this one works:

pure int double_sqr(int x) {
     int z;
     int do_sqr(int y) pure { return y*y; }
     z = do_sqr(x);
     z += do_sqr(x);
     return z;
}



More information about the Digitalmars-d mailing list