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:
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
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
:+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
A function which is not bound to a term.
In the expression
List.map (a -> a + 1) [1, 2, 3]the first argument to
a -> a Nat.+ 1,is the lambda or anonymous function.