Arrays

Arrays are growable, indexed collections. Most operations return new arrays - the original stays untouched. push and pop are the exceptions, mutating in place.

Arrays are created with [] syntax.

fn main() {
  nums = [10, 20, 30, 40, 50]

Access elements by index.

  println(nums[0])
  println(nums[4])
  println(nums.len)

push and pop mutate in place. The array must be mut.

  mut items = [1, 2, 3]
  push(items, 4)
  println(items)
  last = pop(items)
  println(last)
  println(items)

slice returns a new array. The original is unchanged.

  middle = nums.slice(1, 4)
  println(middle)
  println(nums)

reverse also returns a new array.

  println(nums.reverse())
  println(nums)

Search operations.

  println(nums.contains(30))
  println(nums.index_of(40))
  println(nums.contains(99))

Iterate with for..in.

  for n in nums {
    println(n)
  }

for..in range for numeric loops.

  mut sum = 0
  for i in range(nums.len) {
    sum += nums[i]
  }
  println(sum)
}
$ pyr run arrays.pyr
10
50
5
[1, 2, 3, 4]
4
[1, 2, 3]
[20, 30, 40]
[10, 20, 30, 40, 50]
[50, 40, 30, 20, 10]
[10, 20, 30, 40, 50]
true
3
false
10
20
30
40
50
150