Tutorial :Is there a programming language where the static data type is optional?


I'm thinking something where the following two are equivalent:

 int [] array = { 1,2,3,4 }   foreach( int i in array ) {      print i    }       array = { 1,2,3,4 }   foreach( i in array ) {       print i    }  


Yes, languages that have type inference work this way. The code is statically typed, but the compiler can figure out that if you write { 1,2,3,4 }, then anything you assign that to, or call with that, is of type int[]. It saves a lot of (finger) typing.


C# allows you to use the var keyword in declarations to infer the type from the right hand side of the assignment.


you can do it in C++0x, although the type wouldn't be an array:

auto numbers = {1, 2, 3, 4}; // initializer list  for(int i : numbers)  {    cout << i;  }  


In some flavours of BASIC, the type of a constant was determined from its value.

CONST X = 1 ''integer  CONST PI = 3.14 ''float  CONST S = "Hello World" ''string  


python works in a similar fashion to this.


In Lua there is only one numeric type.

  array = { 1,2,3,4 }  for i,v in ipairs(array) do    print(v)  end  


Works even in Powerbuilder (PB.NET):

integer a[] = {1,2,3}  ...  a = { 3,2,1 }  


C# 3.0 has this as well. For instance:

var s = "hello world";  

compiles the same as:

string s = "hello world";  

Works for other data types as well, just giving an example.

There is a difference, BTW, between type inference and loosely-typed languages. With type inference, there is still strong typing, so once the type has been established by initialization, it cannot be changed and performs just as well as if the type were specified explicitly. Loosely-typed languages, however (like the "Variant" type in VBA), allow the same variable to be set to values of different types at runtime.


F#, CAML/OCAML, Haskell and Boo have type inference that generally behaves like what you are describing. Functional languages tend to have even more powerful type inference than this example.


You can also do this with templates in C++. Perl 6 will also be able to do this on it's various built-in data types.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »