#[] is reader syntax for constructing, pattern matching, and typing fixed-arity heterogeneous tuples (Tuple through Tuple8).
Syntax
;; Tuple construction (2 to 8 elements)
#[⟨expr⟩ ⟨expr⟩+]
;; Tuple pattern (2 to 8 elements)
#[⟨pattern⟩ ⟨pattern⟩+]
;; Tuple type (2 to 8 elements)
#[⟨type⟩ ⟨type⟩+]
Semantics
- Arity selects the tuple type and constructor:
- 2 elements:
coalton/classes:Tuple - 3 elements:
coalton/tuple:Tuple3 - 4 elements:
coalton/tuple:Tuple4 - 5 elements:
coalton/tuple:Tuple5 - 6 elements:
coalton/tuple:Tuple6 - 7 elements:
coalton/tuple:Tuple7 - 8 elements:
coalton/tuple:Tuple8
- 2 elements:
- Unsupported arities are errors:
#[](useUnitfor a 0-tuple),#[x](usecoalton/monad/identity:Identityfor a 1-tuple), and tuples with 9 or more elements are rejected. - Construction:
#[e1 ... en]evaluates its elements left-to-right and applies the corresponding tuple constructor. - Pattern matching:
#[p1 ... pn]is valid anywhere a pattern is accepted, includingmatch,define,fn, shorthand(let #[...] = ...),do, and=. - Type syntax:
#[T1 ... Tn]is valid anywhere a type is accepted. Compound element types such as function types must be parenthesized (e.g.,#[(Integer -> String) Boolean]), while outer parentheses around#[...]are not required (e.g.,List #[Integer String]). - Printing:
cl:print-object(when*print-readably*is false) andcoalton/show:ShowformatTuplethroughTuple8values as#[...]. Under*print-readably*,cl:print-objectfalls back to readable#.(...)notation.- Fully applied
TuplethroughTuple8types print as#[...], while partially applied constructors such asTupleor(Tuple :a)retain their named form. - Non-exhaustive match diagnostics print missing tuple patterns as
#[...].
Examples
;; Construction and printing
(coalton #[1 "hello"])
; => #[1 "hello"]
(coalton #[1 "hello" True])
; => #[1 "hello" T]
(coalton (show-as-string #[1 "hello" True]))
; => "#[1 \"hello\" True]"
;; Types and pattern matching in `define`, `match`, and shorthand `let`
(coalton-toplevel
(declare swap (#[:a :b] -> #[:b :a]))
(define (swap #[a b])
#[b a])
(declare sum-triple (#[Integer Integer Integer] -> Integer))
(define (sum-triple triple)
(let #[a b c] = triple)
(+ a (+ b c)))
(declare describe-pair (#[Boolean (Optional Integer)] -> String))
(define (describe-pair pair)
(match pair
(#[(True) (Some n)] (show-as-string n))
(#[(True) (None)] "missing")
(#[(False) _] "disabled"))))
;; Combining `#[]` with collection comprehensions
(coalton
(the (List #[UFix UFix])
[#[x (* x x)] :for x :below 4]))
; => (#[0 0] #[1 1] #[2 4] #[3 9])