Idea: Reverse Type Inference

Moritz Maxeiner via Digitalmars-d digitalmars-d at puremagic.com
Mon May 22 03:29:16 PDT 2017


On Monday, 22 May 2017 at 10:13:02 UTC, 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, 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.

AFAICT this should be possible purely with changes to the 
compiler frontend (no language changes), yes?
Regardless, this would be nice to have, because imho this (from 
your examples):

---
int dec = "1234".convert;
---

is easier to review than this:

---
auto dec = "1234".convert!int;

and I'm all for making code more readable. I must object against 
usage of this though:

---
auto a = "1234".convert.square;
---

No way for a reviewer to easily guess the type of a without 
inspecting all functions.


More information about the Digitalmars-d mailing list