Automatic typing

Ary Borenszweig ary at esperanto.org.ar
Sat Jun 29 12:18:13 PDT 2013


On 6/27/13 9:34 PM, JS wrote:
> Would it be possible for a language(specifically d) to have the ability
> to automatically type a variable by looking at its use cases without
> adding too much complexity? It seems to me that most compilers already
> can infer type mismatchs which would allow them to handle stuff like:
>
> main()
> {
>     auto x;
>     auto y;
>     x = 3;   // x is an int, same as auto x = 3;
>     y = f(); // y is the same type as what f() returns
>     x = 3.9; // x is really a float, no mismatch with previous type(int)
> }
>
> in this case x and y's type is inferred from future use. The compiler
> essentially just lazily infers the variable type. Obviously ambiguity
> will generate an error.

What you are asking is essentially what Crystal does for all variables 
(and types):

https://github.com/manastech/crystal/wiki/Introduction#type-inference

Your example would be written like this:

x = 3
y = f()
x = 3.9

But since Crystal transforms your code to SSA 
(http://en.wikipedia.org/wiki/Static_single_assignment_form) you 
actually have *two* "x" variables in your code. The first one is of type 
Int32, the second of type Float64. The above solves the problem 
mentioned by Steven Schveighoffer, where you didn't know what overloaded 
version you was calling:

x = 3
f(x) # always calls f(Int32), because at run-time
      # x will always be an Int32 at this point
x = 3.9

But to have this in a language you need some things:

1. Don't have a different syntax for declaring and updating variables
2. Transform your code to SSA
(maybe more?)

So this is not possible in D right now, and I don't think it will ever 
be because it requires a huge change to the whole language.


More information about the Digitalmars-d mailing list