Idea: Reverse Type Inference

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Mon May 22 06:39:46 PDT 2017


On 22.05.2017 12:13, Sebastiaan Koppe wrote:
> I work with Scala professionally. I often feel its type inference for
> generics/templates is better than D's; as long as it can find a type
> _anywhere_ it will use that, no matter where it needs to pull it from.
>
> Over the past weeks I have been noticing a specific case where it
> happens. I call it reverse type inference, simply because it goes
> against the normal evaluation order.
>
> While it is only syntactic sugar,

(It's not.)

> I think it would be nice to have in D
> and I want to know what you guys think about it.
>
> Some examples:
>
> ---
>
> T convert(T)(string s) { ... }
>
> auto dec = "1234".convert!int;   // normal
> int dec = "1234".convert;        // T of convert is inferred due to type
> declaration of dec
>
> int square(int t) { ... }
>
> auto a = "1234".convert.square;  // since square accepts int, T of
> convert is inferred to be int
>
> ---
>
> p.s. I am not asking anyone to build it. I just want to have the idea
> out there. And if time allows I might take a stab at implementing it.

I'm in favour. Note that this already happens in some circumstances, 
e.g. the parameter type of the delegate is inferred here from the 
expected type:

int delegate(int) dg = x=>x;

I suspect your enhancement might actually be easy to implement by 
reusing the same mechanism in the compiler. (I.e. defer the template 
instantiation if forward inference is incomplete, and then deduce the 
remaining template arguments in "matchType".)


Another annoying case:

alias Fun(A,B) = B delegate(A);

B apply(A,B)(Fun!(A,B) f, A a){ return f(a); }

void main(){
     apply(x=>x,2); // error
}








More information about the Digitalmars-d mailing list