#You can use pattern matching to run different
#functions based on which parameters you pass
#This example uses pattern matching to start,
#run, and end a recursive function
defmodule Counter do
def count_to do
count_to(100, 0) #No argument, init with 100
end
def ...
You can also pattern match on Elixir Data Structures such as Lists.
Lists
Matching on a list is quite simple.
[head | tail] = [1,2,3,4,5]
# head == 1
# tail == [2,3,4,5]
This works by matching the first (or more) elements in the list to the left hand side of the | (pipe) and the rest of the ...
defmodule Math do
# We start of by passing the sum/1 function a list of numbers.
def sum(numbers) do
do_sum(numbers, 0)
end
# Recurse over the list when it contains at least one element.
# We break the list up into two parts:
# head: the first element of the list
# ta...
{ a, b, c } = { "Hello", "World", "!" }
IO.puts a # Hello
IO.puts b # World
IO.puts c # !
# Tuples of different size won't match:
{ a, b, c } = { "Hello", "World" } # (MatchError) no match of right hand side value: { "Hello",...