Skip to content

Instantly share code, notes, and snippets.

@aneyzberg
Last active April 8, 2018 12:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aneyzberg/5cec0f73c6454e5ad0255b0538d650ed to your computer and use it in GitHub Desktop.
Save aneyzberg/5cec0f73c6454e5ad0255b0538d650ed to your computer and use it in GitHub Desktop.
Pattern Matching
iex(9)> Greeter.hello(:jane)
"Hello Jane"
iex(10)> Greeter.hello(:anna)
"Hello anna"
# calculator.exs
defmodule Calculator do
  def multiply_by_two([]), do: return []

  def multiply_by_two([head | tail]) do 
    [head * 2 | multiply_by_two(tail)]
  end
end
iex> Calculator.mulitply_by_two([])
[]

iex> Calculator.multiply_by_two([1, 2, 3])
[2, 4, 6]
iex> a = 1
1
iex> 2 = a
** (MatchError) no match of right hand side value: 1
iex(8)> b = 2
2
iex(9)> b = 3 
3
iex(1)> a = 1
1
iex(2)> b = 3 
1
iex(3)> ^b = 4 
** (MatchError) no match of right hand side value: 4

iex(3)>
[/code]
iex(12)> {result, value} = {:ok,2}
{:ok, 2}
iex(13)>
iex(12)> {result, value} = {:ok,2}
{:ok, 2}
iex(13)> value
2
iex(12)> {:ok, value} = {:notok, 2}
** (MatchError) no match right hand side value: {:notok,2}
# greeter.exs
defmodule Greeter do
  def hello(:jane), do: "Hello Jane"
  
  def hello(name) do
    "Hello #{name}"
  end
end
  iex(6)> a = 1
  1
  iex(7)> b = 2 
  2
  iex(6)> a = 1
  1
  iex(7)> b = 2 
  2
@jgburet
Copy link

jgburet commented Nov 1, 2017

Mistake on https://gist.github.com/aneyzberg/5cec0f73c6454e5ad0255b0538d650ed#file-pattern-matching-5-md
I guess you meant

iex(2)> b = 3 
3

(and without that [/code] keyword)

@junjizhi
Copy link

junjizhi commented Apr 8, 2018

iex(5)> 2 = b
** (CompileError) iex:5: undefined function b/0

I guess elixir doesn't support variable matching in the right side?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment