www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Pure tail call optimization

reply "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
Today, while playingly adding const annotations to std.bigint, I noticed  
that I ended up with a few casts - or more specifically, assumeUniques.

Now, the interesting thing was the pattern they formed. Almost invariably,  
it's like this:
     BigUint foo() pure {
         uint[] result;
         //...
         return BigUint(assumeUnique(result));
     }

Now, had I instead returned uint[] directly, an external function could  
take advantage of the fact that the function was pure:

     uint[] fooImpl() pure {
         uint[] result;
         //...
         return result;
     }

     BigUint foo() pure {
         return BigUint(fooImpl());
     }

As one can clearly see, this removes the need for assumeUnique. However,  
it also complicates the design. Lastly, given that the compiler already  
knows the return value of a pure function is magical, it seems it should  
be possible to exploit that also here.

I will therefore suggest that when the return statement of a pure function  
consists of a single call to another pure function, and there is no  
possibility of aliasing of arguments, the arguments to that call may be  
treated as immutable.

Destroy.

--
   Simen
Nov 01 2013
parent "deadalnix" <deadalnix gmail.com> writes:
On Friday, 1 November 2013 at 18:12:28 UTC, Simen Kjaeraas wrote:
 Today, while playingly adding const annotations to std.bigint, 
 I noticed that I ended up with a few casts - or more 
 specifically, assumeUniques.

 Now, the interesting thing was the pattern they formed. Almost 
 invariably, it's like this:
     BigUint foo() pure {
         uint[] result;
         //...
         return BigUint(assumeUnique(result));
     }

 Now, had I instead returned uint[] directly, an external 
 function could take advantage of the fact that the function was 
 pure:

     uint[] fooImpl() pure {
         uint[] result;
         //...
         return result;
     }

     BigUint foo() pure {
         return BigUint(fooImpl());
     }

 As one can clearly see, this removes the need for assumeUnique. 
 However, it also complicates the design. Lastly, given that the 
 compiler already knows the return value of a pure function is 
 magical, it seems it should be possible to exploit that also 
 here.

 I will therefore suggest that when the return statement of a 
 pure function consists of a single call to another pure 
 function, and there is no possibility of aliasing of arguments, 
 the arguments to that call may be treated as immutable.

 Destroy.

 --
   Simen
isolated. I think that will become my answer to most problem as of now :D
Nov 02 2013