Idea: Reverse Type Inference
via Digitalmars-d
digitalmars-d at puremagic.com
Tue May 23 07:55:40 PDT 2017
On Monday, 22 May 2017 at 13:39:46 UTC, Timon Gehr wrote:
> 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
> }
Interesting. BTW, what do you think about this feature being
extended to implicit template instantiations a la Rust:
https://doc.rust-lang.org/book/generics.html#resolving-ambiguities ?
In Kotlin they have a related feature called smart casts:
https://kotlinlang.org/docs/reference/typecasts.html
(also briefly shown here
https://www.youtube.com/watch?v=X1RVYt2QKQE&t=1569s)
Which of course is a subset of the more general area of control
flow based type analysis. Typescript is good example of bringing
those things to the JS world:
https://www.youtube.com/watch?v=d1f6VBmWg6o&t=39m39s
https://blog.mariusschulz.com/2016/09/30/typescript-2-0-control-flow-based-type-analysis
More information about the Digitalmars-d
mailing list