Lists
Make a list #
A list holds values of one type, in order. Its type is written List[T].
def main() -> Void
numbers = [3, 1, 2]
names = ["Ana", "Bob"]
puts(numbers)
puts(names.size)
endOutput
[3, 1, 2]
2Mixing types in a list is an error:
def main() -> Void
mixed = [1, "two"]
endDoes not compile
error[CHECK-TYPE-MISMATCH]An empty list needs a known type, for example from an annotation:
def main() -> Void
todo: List[String] = []
puts(todo.size)
endOutput
0Read elements #
Indexes start at 0. An index outside the list stops the program.
def main() -> Void
letters = ["a", "b", "c"]
puts(letters[0])
puts(letters[2])
endOutput
a
cdef main() -> Void
letters = ["a", "b", "c"]
puts(letters[3])
endRuntime error
error[RUNTIME-INDEX-OUT-OF-RANGE]Add and change #
Lists never change in place. push gives a new list with one more element. set gives a new list with one element replaced. + joins two lists into a new one.
def main() -> Void
xs = [1, 2]
xs = xs.push(3)
xs = xs.set(0, 10)
puts(xs)
puts(xs + [4, 5])
endOutput
[10, 2, 3]
[10, 2, 3, 4, 5]xs[0] = 10 does not exist. Use set.
Walk a list #
Use for, or each with a block:
def main() -> Void
for n in [1, 2]
puts(n)
end
["x", "y"].each do |s| puts(s) end
endOutput
1
2
x
yTransform #
map, select and reduce take a block and give a new value:
def main() -> Void
xs = [1, 2, 3, 4, 5]
puts(xs.map do |x| x * x end)
puts(xs.select do |x| x > 2 end)
puts(xs.reduce(0) do |sum, x| sum + x end)
endOutput
[1, 4, 9, 16, 25]
[3, 4, 5]
15Sort, take, drop #
def main() -> Void
xs = [5, 3, 8, 1]
puts(xs.sort)
puts(xs.reverse)
puts(xs.take(2))
puts(xs.drop(2))
endOutput
[1, 3, 5, 8]
[1, 8, 3, 5]
[5, 3]
[8, 1]sort_by sorts by a key that a block gives:
def main() -> Void
words = ["pear", "fig", "banana"]
puts(words.sort_by do |w| w.length end)
endOutput
["fig", "pear", "banana"]Ask questions #
def main() -> Void
xs = [2, 4, 7]
puts(xs.any? do |x| x > 5 end)
puts(xs.all? do |x| x % 2 == 0 end)
endOutput
true
falseLists of lists #
def main() -> Void
grid = [[1, 2], [3, 4]]
puts(grid[1][0])
puts(List.repeat(0, 3))
endOutput
3
[0, 0, 0]Prefer for or each to visit every element. See the List library page for every function.