Tuples and data types can be decomposed withpattern matching,but Unison also provides several ways to more concisely bind variable names to the corresponding parts of a data structure.
Destructuring tuples
Variables can be assigned to the constituent parts of a tuple by surrounding the variable definition with parentheses and separating the variables with commas.
🎨If a tuple is passed as an argument to alambda,you can use thecases
keyword as a way to destructure the tuple.
Destructuring data types
The fields of a data type can also be bound to variables by destructuring theirdata constructors
Say you have a simpledestructuringBinds.Box
type:
unique type destructuringBinds.Box a
unique type destructuringBinds.Box a = Box a
You could write a function that adds twoBox Nat
types together by accessing theNat
elements like this:
addBox :
destructuringBinds.Box Nat -> destructuringBinds.Box Nat -> Nat
addBox boxA boxB =
use Nat +
use destructuringBinds.Box Box
(Box a) = boxA
(Box b) = boxB
a + b
So destructuring a data type takes the form(DataConstructor field1 field2 … fieldN) = instanceOfDataType
Usage notes
Currently, Unison does not support decomposition interm definitions,so a function which accepts a tuple or data type as a parameter cannot be destructured when the function parameter is first named. This means atermDeclarationlikeaddTwo : (Nat, Nat) -> Nat
can notbe implemented with a term definition which starts withaddTwo (one,two) = one + two
.The decomposition of the tuple would have to be done on a separate line.
In some languages you can use list constructors likeList.+:
or:+
to name separate elements in the list. We do not currently support that feature for term definitions, but youcanuse them in pattern matching; seelist pattern matchingfor more details.
-- you can't do this
list = [1,2,3,4]
one +: tail = list
list = [1, 2, 3, 4]
(one +: tail) = list