Lists and Tuples
nil, ::, [], (a,b,c)
Lists and tuples are SML's main ways to group values.
Tuples have a fixed length; each component can have a different type.val p = (1, "one", true);
The type is int * string * bool. Access components with pattern matching:val (n, s, b) = p; binds n=1, s="one", b=true.
Lists have arbitrary length; all elements must share one type. Per Def 1.12 (slides p.211), lists have two constructors:
- nil (written []) — the empty list.
- :: (pronounced "cons") — prepends one element to a list.
So [1, 2, 3] is sugar for 1 :: 2 :: 3 :: []. The list [1, 2, 3] has type int list; [1, "a"] is a TYPE ERROR because int and string differ.
Pattern matching (Def 1.6) lets you destructure structured values:val (x, _) = (10, 20); binds x = 10; the _ is an anonymous variable (Def 1.8) — we don't care about that component. This is the foundation for the case expression we'll use on lists and datatypes.
- 0.0sLists in SML
- 1.4sPhase one: brackets and a single cell [1]
- 3.2sPhase two: cell 2 slides in to make [1, 2]
- 5.7sPhase three: cell 3 arrives, list becomes [1, 2, 3]
- 8.4sPhase four: cons 4 :: [1, 2, 3] prepends 4
- 11.8sPhase five: rev [1, 2, 3] builds [3, 2, 1] off to the right
- 15.5sArrows show the reorder; lists are linked cells
- 17.0sLists are linked cells; cons prepends; rev reverses
The set of all functions from set to set is itself a set, written or . We can apply set operations to function spaces: .
Examples:
- is the set of all boolean functions of one boolean argument. There are such functions (constant true, constant false, identity, negation).
- is the set of all sequences of naturals.
An indexed family is a set indexed by another set: where is the index set. The order is irrelevant — what matters is the function .
Examples:
- The rows of a database table: indexed by row id.
- The coefficients of a polynomial: — coefficients indexed by .
- The pages of a book: indexed by page numbers.
The indexed family is a function from the index set to the value set: with .
A k-ary relation on sets is a subset of . So:
- Binary relation: (the usual case).
- Ternary relation: (e.g. 'between': is between and ).
- k-ary: .
A k-ary function takes arguments and returns one value. Equivalently, corresponds to a (k+1)-ary relation .
(1, "a", true)?[1, 2, 3] syntactic sugar for?[1, "a"] a valid SML list?_ mean in val (x, _) = (3, 7)?[] (when its context does not fix the element type)?