This task is about arrays.

For hashes or associative arrays, please see Creating an Associative Array.

For a definition and in-depth discussion of what an array is, see Array.



Task

Show basic array syntax in your language.

Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).

Please discuss at Village Pump:   Arrays.

Please merge code in from these obsolete tasks:

   Creating an Array
   Assigning Values to an Array
   Retrieving an Element of an Array


Related tasks

   Collections
   Creating an Associative Array
   Two-dimensional array (runtime)


import util.
 
go =>
 
   % Create an array of length 10
   Len = 10,
   A = new_array(Len),
   bind_vars(A,0), % Initialize all values to 0
   println(a=A),
   A[1] := 1, % Assign a value
   println(a=A),
   println(a1=A[1]), % print first element
   % (re)assign a value
   foreach(I in 1..Len) A[I] := I end,
   println(A[3..7]), % print some interval of an array
   nl,
 
   % 2D arrays
   A2 = new_array(4,4),
   foreach(I in 1..4, J in 1..4) 
     A2[I,J] := (I-1)*4+J
   end,
   foreach(Row in A2) println(Row) end,
 
   % These functions are defined in the util module.
   % They returns lists so we have to convert them to arrays.
   println('rows     '=to_array(A2.rows)), 
   println('columns  '=A2.columns.to_array),
   println(diagonal1=A2.diagonal1.to_array),
   println(diagonal2=A2.diagonal2.to_array),
 
   nl,
 
   % Pushing values to an array 
   A3 = {}, % an empty array
   foreach(I in 1..4)
     A3 := A3 ++ {10**I+I}
   end,
   println(a3=A3),
   nl,
 
   % Some misc functions
   println([first=A3.first(), second=A3.second(),last=A3.last()]),
 
   nl.
 