Difference between revisions of "Declare an array"

From CodeCodex

(Java)
Line 23: Line 23:
 
Populating an array with values upon declaration:     
 
Populating an array with values upon declaration:     
 
  String[][] twoDimension = { {"1","2","3"}, {"4","5","6"}, {"7","8","9"} };
 
  String[][] twoDimension = { {"1","2","3"}, {"4","5","6"}, {"7","8","9"} };
 +
 +
===Lisp===
 +
<pre>
 +
* #(1 2 3)
 +
 +
#(1 2 3)
 +
</pre>
 +
 
===OCaml===
 
===OCaml===
 
No need for type declarations in OCaml, thanks to type inference. OCaml has homogeneous arrays and provides array literals. For example:
 
No need for type declarations in OCaml, thanks to type inference. OCaml has homogeneous arrays and provides array literals. For example:

Revision as of 22:51, 1 August 2006

This task should distinguish between languages that only allow array literals when declaring arrays (e.g. C, C++, Java) and languages that allow array literals to be arbitrary expressions (e.g. OCaml, Lisp).

Implementations

Java

One dimension

String[] oneDimension;

or

String[] oneDimension[];

or

String oneDimension[];

Populating an array with values upon declaration:

String[] oneDimension = { "a","b","c" };

Two dimension

String[][] twoDimension;

or

String[][] twoDimension[][];

or

String twoDimension[][];

Populating an array with values upon declaration:

String[][] twoDimension = { {"1","2","3"}, {"4","5","6"}, {"7","8","9"} };

Lisp

* #(1 2 3)

#(1 2 3)

OCaml

No need for type declarations in OCaml, thanks to type inference. OCaml has homogeneous arrays and provides array literals. For example:

# [|1; 2; 3|];;
- : int array = [|1; 2; 3|]

Note that array literals improve upon C-style (e.g. C++ and Java) array declarations because OCaml's array literals can be used anywhere (they are expressions) whereas the C-style is only valid on the right-hand side of an array declaration. For example, you can apply an array literal as a function argument directly in OCaml:

# Array.fold_left ( + ) 0 [|1; 2; 3|];;
- : int = 6

Visual Basic (3-6)

One Dimensional

Fixed Length Array:

Dim Variable(5) as string

Variable Length Array:

Dim Variable() as string

Two Dimensional

Fixed by Fixed Length Array:

Dim Variable(5,2) as string

Fixed by Variable Length Array:

Dim Variable(5,) as string

Variable by Variable Length Array:

Dim Variable(,) as string