Array and sequence types

Arrays are a homogeneous type, meaning that each element in the array has the same type. Arrays always have a fixed length specified as a constant expression (except for open arrays). They can be indexed by any ordinal type. A parameter A may be an open array, in which case it is indexed by integers from 0 to len(A)-1. An array expression may be constructed by the array constructor []. The element type of this array expression is inferred from the type of the first element. All other elements need to be implicitly convertible to this type.

An array type can be defined using the array[size, T] syntax, or using array[lo..hi, T] for arrays that start at an index other than zero.

Sequences are similar to arrays but of dynamic length which may change during runtime (like strings). Sequences are implemented as growable arrays, allocating pieces of memory as items are added. A sequence S is always indexed by integers from 0 to len(S)-1 and its bounds are checked. Sequences can be constructed by the array constructor [] in conjunction with the array to sequence operator @. Another way to allocate space for a sequence is to call the built-in newSeq procedure.

A sequence may be passed to a parameter that is of type open array.

Example:

  1. type
  2. IntArray = array[0..5, int] # an array that is indexed with 0..5
  3. IntSeq = seq[int] # a sequence of integers
  4. var
  5. x: IntArray
  6. y: IntSeq
  7. x = [1, 2, 3, 4, 5, 6] # [] is the array constructor
  8. y = @[1, 2, 3, 4, 5, 6] # the @ turns the array into a sequence
  9. let z = [1.0, 2, 3, 4] # the type of z is array[0..3, float]

The lower bound of an array or sequence may be received by the built-in proc low(), the higher bound by high(). The length may be received by len(). low() for a sequence or an open array always returns 0, as this is the first valid index. One can append elements to a sequence with the add() proc or the & operator, and remove (and get) the last element of a sequence with the pop() proc.

The notation x[i] can be used to access the i-th element of x.

Arrays are always bounds checked (statically or at runtime). These checks can be disabled via pragmas or invoking the compiler with the --boundChecks:off command-line switch.

An array constructor can have explicit indexes for readability:

  1. type
  2. Values = enum
  3. valA, valB, valC
  4. const
  5. lookupTable = [
  6. valA: "A",
  7. valB: "B",
  8. valC: "C"
  9. ]

If an index is left out, succ(lastIndex) is used as the index value:

  1. type
  2. Values = enum
  3. valA, valB, valC, valD, valE
  4. const
  5. lookupTable = [
  6. valA: "A",
  7. "B",
  8. valC: "C",
  9. "D", "e"
  10. ]