views:

155

answers:

10

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 
 }
+5  A: 

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

Greg Hewgill
+9  A: 

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.

Adam Goode
Type inference... that's what I'm looking for ( I think ) :)
OscarRyz
+3  A: 

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;
}
AraK
+1  A: 

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
Artelius
+1  A: 

python works in a similar fashion to this.

GSto
In what sense do you claim "Python works in a similar fashion" to this?
Gregg Lind
x = int(42)x = 42are equivalent in python
GSto
+1  A: 

In Lua there is only one numeric type.

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

Works even in Powerbuilder (PB.NET):

integer a[] = {1,2,3}
...
a = { 3,2,1 }
Anders K.
A: 

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.

s1n
+1  A: 

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.

richardtallent
+1  A: 

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.

JasonTrue