Try Install Learn Blog API Packages GitHub
Pages

Arrays

An Array is a generic type containing elements of any other type.

Type

The type of a generic array is Array(a) where the parameter is the type of it's items.

Syntax

Arrays are typically created with an array literal:

[1, 2, 3]
["A", "B", "C"]

Type

You can define the type of an array using the of keyword. It is useful for defining the type of an empty array:

[] of Number
[1,2,3] of Number

Accessing Items

We can access an arrays item at a given index using the following syntax:

array =
  [1, 2, 3]

array[0]

When accessing an item this way the type of the item will be Maybe(a) where a is the type of item in the array.

This is so because there might not be an item at that index.

Pattern Matching

We can use pattern matching in a case expression in order to match certain values or get items of the array:

case (["A", "B", "C"]) {
  [] => ""                /* Empty array  */
  ["a"] => ""             /* Array with only one specific element */
  [a] => ""               /* Array with only one element */
  [a, b] => ""            /* Array with only two elements */
  [a, ...middle, b] => "" /* Array at least with two elements (middle can be empty) */
  [...head, tail] => ""   /* Array at one element (head can be empty) */
  [head, ...tail] => ""   /* Array at one element (tail can be empty) */
  [...items] => ""        /* Items would be the array */
  => ""                   /* Fallback as usual */
}

The type checker will raise an error if the case is not exhaustive.