Collections
Fuyu has several collection types; however, there are two with first-class syntax support: tuples and lists.
Tuple
A tuple is an ordered collection of values of arbitrary types. Tuples are
created with (...)
and may have zero or more elements. Tuples are useful for
representing a single value (i.e., ()
) and for grouping multiple values
together. When a 1-tuple is required, it must have a trailing ,
.
() // 0-tuple, called "unit".
(3.14,) // 1-tuple, trailing comma is required.
("hello", "world") // 2-tuple.
(True, "text", [5, 6, 7]) // 3-tuple.
The type of a tuple is simply the tuple of the types of each element.
let a: () = ()
let b: (Int,) = (3.14,)
let c: (String, String) = ("hello", "world")
let d: (Bool, String, List[Int]) = (True, "text", [5, 6, 7])
Elements of a tuple can be accessed in two ways:
- Destructuring uses pattern matching to capture values from a tuple.
- Dead reckoning is more compact and generally more useful when only a
single element from a tuple is required. Elements are accessed with
.#n
, where#n
is the zero-indexed position of the element in the tuple.
let xyz = (7, 15, 3)
// Destructuring.
let (x, y, z) = xyz
assert_eq(y, 15)
// Dead reckoning.
assert_eq(xyz.1, 15)
List
A List
is an ordered collection of values belonging to the same type. Lists
are created with [..]
, may have any length (including zero). Lists are type
parameterized, which means that the type of a list depends on the type of the
values it holds. For example, a list of integers (List[Int]
) and a list of
strings (List[String]
) are two different types.
let a: List[Bool] = [] // Empty.
let b: List[Int] = [1, 2, 3]
let c = ["one", "two", "three"]
List elements can be accessed with destructuring or dead reckoning.
let xs = [6, 7, 9]
// Destructuring.
match xs {
[x, ..rs] => {
assert_eq(x, 6)
assert_eq(rs, [7, 8])
}
_ => unreachable()
}
// Dead reckoning.
assert_eq(xs[0], 6)
assert_eq(xs[1], 7)
assert_eq(xs[2], 8)
The ..
spreading operator was used to match the rest of a list. The use of
spreading is discussed in greater detail with patterns; however,
spreading can also be used to create new lists from existing ones.
let start = [1, 2, 3]
let middle = [5, 6]
let xs = [..start, 4, ..middle, 7]
assert_eq(xs, [1, 2, 3, 4, 5, 6, 7])