Pattern matching on
Listelements has its own special syntax. Thegoes in-depth about the data structure itself, check it out!
You can use pattern matching to scrutinize the first (left-most) element of a list with the
match ["a", "b", "c"] with head +: tail -> head _ -> "empty list"⧨"a"
+:is unpacking the first element
headto its text value
"a"while keeping the remaining elements
List.The underscore will match the "empty list" case. We could have also expressed
_ -> "empty list"as
 -> "empty list"or
List.empty -> "empty list".All three are valid ways of testing for the empty list case.
You can also pattern match on thelast(right-most) element of a list in Unison:
match ["a", "b", "c"] with firsts :+ last -> last _ -> "empty list"⧨"c"
Let's say you wanted to pattern match on the first 2 elements of a given list. It might betemptingto do a multi item pattern match with successive
+:operators,but recall thatfunction applicationfor operators always starts at the leftmost sub-expression.
🙅🏻♀️ This will not work:
match ["a","b","c"] with first +: second +: remainder -> "nope" _ -> "empty list"
first +: secondis expecting
secondto be a type
List,but what we're trying to express is that it's the unwrapped second element. Instead, if you want to pattern match on a particular list segment length or list segment values, you can use the
[_]list constructor syntax!
Our example above can be rewritten:
match ["a", " b", "c "] with [first, second] ++ remainder -> use Text ++ first ++ " yes!" _ -> "fallback"⧨"a yes!"
Or if we don't care about binding the list elements to variables, we can use underscores to pattern match on any list that has exactly
match ["a", " b", "c "] with [_, _] ++ remainder -> "list has at least two elements" _ -> "fallback"⧨"list has at least two elements"
Operators are functions which are called in an infix manner, as in
5 Nat.* 8.They're commonly expressed in terms of short symbols like
Nat.* : Nat -> Nat -> Nat
<|> : Weighted a -> Weighted a -> Weighted a
Function application refers to the way in which a language evaluates a function and its arguments when it is called.
For a function
ftaking an argument
x,it's common to say "we apply
See the language reference section onfunction applicationfor Unison specifics.