Automatic typing

Ary Borenszweig ary at esperanto.org.ar
Mon Jul 1 06:39:38 PDT 2013


On 6/30/13 7:39 PM, JS wrote:
> On Saturday, 29 June 2013 at 19:18:13 UTC, Ary Borenszweig wrote:
>> 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.
>
> This is not what I am talking about and it seems quite dangerous to have
> one variable name masquerade as multiple variables.

Why dangerous? I've been programming in Ruby for quite a time and never 
found it to be a problem, but an advantage. Now I'm programming in 
Crystal and it's the same, but the compiler can catch some errors too.

Show me an example where this is dangerous (the pointer example gave by 
Walter is not valid anymore since it has a fix).



More information about the Digitalmars-d mailing list