Idea: Reverse Type Inference

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Tue May 23 14:59:02 PDT 2017


On 23.05.2017 16:55, Petar Kirov [ZombineDev] wrote:
> On Monday, 22 May 2017 at 13:39:46 UTC, Timon Gehr wrote:
>> ...
>> 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 ?
> ...

This is easier to pull off in Rust, where generics are more limited and 
there are no implicit conversions, but it could work, to a useful 
extent. It's less likely to happen though, because so far, all type 
deduction happens locally (except attributes). I don't think the 
compiler is set up to very easily migrate to a system where type 
deduction and implicit template instantiation can happen at a distance.


> 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)
> ...

This is cheap for them to support, as everything is a class reference 
and they do null safety the same way. In D, not every type is a class, 
and language magic causes friction, so user-defined types would need to 
be able to customize such an analysis in some way. (E.g. typestate.)


> 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 
> 

This only works really well if types do not implicitly affect execution. 
D has e.g. opAssign, based on the assumption that types of variables do 
not change. Also, in D, types are used to determine memory layout.


They don't seem to take it very far though. (E.g. it does not seem to 
support polymorphic record updates from what I can see).


More information about the Digitalmars-d mailing list