Return type inference

Peter Alexander peter.alexander.au at gmail.com
Thu May 17 07:14:28 PDT 2012


On Thursday, 17 May 2012 at 13:10:20 UTC, Tobias Pankrath wrote:
> For the human reader it is easy to see that the return type of
> foo should be int. Could the following rule be added to make dmd
> see this, too?

> If the function is called recursively the type of the result of 
> this call is inferred in the same way. If the recursive call is 
> part of a return statement >  then this statement is not 
> considered for type inference. If all return statements are 
> discarded in this way, it is an error.

It's not that simple:

--------------------------------
int bar(int x);
real bar(real x);

auto foo(int x)
{
     if (x < 0)
         return bar(foo(x-1));
     return 0;
}
--------------------------------

In order to determine the first return type, it needs to find out 
what overloaded 'bar' to call, which requires determining the 
first return type.

If you ignore the first return statement and only consider the 
int then there could be problems. e.g. if above we had:

real bar(int x);

And we ignored the first return statement then the determined 
return type would be wrong (would infer int, but bar(foo(x-1)) 
would return real).


More information about the Digitalmars-d mailing list