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.
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 the
caseskeyword 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 simple
You could write a function that adds two
Box Nattypes together by accessing the
Natelements like this:
So destructuring a data type takes the form
(DataConstructor field1 field2 … fieldN) = instanceOfDataType
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 atermDeclarationlike
addTwo : (Nat, Nat) -> Natcan notbe implemented with a term definition which starts with
addTwo (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 like
List.:+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