Automatic typing
Steven Schveighoffer
schveiguy at yahoo.com
Thu Jun 27 17:48:22 PDT 2013
On Thu, 27 Jun 2013 20:34:53 -0400, JS <js.mdnq at gmail.com> 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.
>
There are very good reasons not to do this, even if possible. Especially
if the type can change.
Consider this case:
void foo(int);
void foo(double);
void main()
{
auto x;
x = 5;
foo(x);
....
// way later down in main
x = 6.0;
}
What version of foo should be called? By your logic, it should be the
double version, but looking at the code, I can't reason about it. I have
to read the whole function, and look at every usage of x. auto then
becomes a liability, and not a benefit.
Coupling the type of a variable with sparse usages is going to be
extremely confusing and problematic. You are better off declaring the
variable as a variant.
-Steve
More information about the Digitalmars-d
mailing list