Tutorial by Examples

#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 ...
%{username: username} = %{username: "John Doe", id: 1} # username == "John Doe" %{username: username, id: 2} = %{username: "John Doe", id: 1} ** (MatchError) no match of right hand side value: %{id: 1, username: "John Doe"}
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...
f = fn {:a, :b} -> IO.puts "Tuple {:a, :b}" [] -> IO.puts "Empty list" end f.({:a, :b}) # Tuple {:a, :b} f.([]) # Empty list
{ 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",...
fizzbuzz = fn (0, 0, _) -> "FizzBuzz" (0, _, _) -> "Fizz" (_, 0, _) -> "Buzz" (_, _, x) -> x end my_function = fn(n) -> fizzbuzz.(rem(n, 3), rem(n, 5), n) end

Page 1 of 1