values returns zero, one, or multiple values from an expression, destructures multiple values in a shorthand let binding, and (written Values) annotates result-polymorphic type variables in forall.
Syntax
;; Produce zero values (type `Void`)
(values)
;; Produce one or more values (type `⟨type⟩` or `⟨type-1⟩ * ⟨type-2⟩ * ...`)
(values ⟨expr⟩+)
;; Destructure zero, one, or more values in an expression body
(let (values ⟨var-or-_⟩*) = ⟨expr⟩)
;; Result-sequence kind annotation in `forall`
(forall ((:⟨var⟩ Values)) ⟨qualified-type⟩)
Semantics
- Constructing values with
(values ...):(values)produces zero values and has typeVoid.(values ⟨expr⟩)produces a single value and has the same type as⟨expr⟩.(values ⟨expr-1⟩ ⟨expr-2⟩ ...)evaluates its arguments left-to-right and returns multiple values of type⟨type-1⟩ * ⟨type-2⟩ * ...(see*).- Every argument
⟨expr-i⟩tovaluesmust be a single-value expression (Voidand nested multi-value expressions cannot be passed as components ofvalues). - A multi-value expression can appear wherever multiple values are accepted: as the return value of a function (in tail position or via
return), on the right-hand side of(let (values ...) = ...), as a non-final expression inprogn, as the:returnsexpression offor/for*, as the protected expression ofprotect, or in the branches ofif,cond,match,catch, orhandle.
- Destructuring values with
(let (values ...) = ...):- Valid inside any implicit
prognordobody (not inside a block(let (...) ...)binding list). - The number of binders
⟨var-or-_⟩*must match the exact number of values returned by⟨expr⟩(including0for(let (values) = ⟨void-expr⟩)). - Each binder must be an ordinary variable name or
_, and all variable names in the(values ...)list must be distinct.
- Valid inside any implicit
- Kind annotation
Valuesinforall:- In a
forallbinder(:r Values), the same symbolcoalton:Valuesdenotes the kind of an entire result sequence (zero, one, or multiple values). Seeforall.
- In a
Examples
(coalton-toplevel
;; Return two values without heap-allocating a Tuple
(declare min-max (Ord :a => :a * :a -> :a * :a))
(define (min-max a b)
(if (<= a b)
(values a b)
(values b a)))
;; Destructure multiple return values in a function body
(declare span (Integer * Integer -> Integer))
(define (span a b)
(let (values lo hi) = (min-max a b))
(- hi lo))
;; Return zero values (`Void`)
(declare noop (Void -> Void))
(define (noop)
(values)))
Other notes
(values ...)and(let (values ...) = ...)compile directly to Common Lispcl:valuesandcl:multiple-value-bind, avoiding heap allocation of intermediate tuples. See Performance and Optimization.- See
*,->,let, andforall.