The match operator in Elixir
Three matches: destructuring a tuple, splitting a list, and pinning a bound value.
# = is a match, not an assignment: the shape on the left must fit the
# data on the right, and any bare names in it get bound.
{lat, lon} = {44.8, -68.7}
IO.puts("buoy anchored at #{lat}, #{lon}")
[flagship | escorts] = ["Puffin", "Skua", "Tern"]
IO.puts("#{flagship} leads; #{Enum.join(escorts, " and ")} follow")
# The pin operator ^ matches against a bound value instead of rebinding.
tide = "ebb"
{^tide, knots} = {"ebb", 2.5}
IO.puts("#{tide} current at #{knots} knots")
How it works
{lat, lon} = {44.8, -68.7}fits the shape on the left and binds both names.[flagship | escorts]splits the fleet into its head and the list of the rest.^tidepins the existing binding, so the match asserts the value instead of rebinding it.
Keywords and builtins used here
EnumIO
The run, in numbers
- Lines
- 12
- Characters to type
- 477
- Tokens
- 107
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 86 seconds.
Step 1 of 3 in Pattern matching, step 4 of 27 in Language basics.