iex(9)> Greeter.hello(:jane)
"Hello Jane"
iex(10)> Greeter.hello(:anna)
"Hello anna"
Last active
April 8, 2018 12:23
-
-
Save aneyzberg/5cec0f73c6454e5ad0255b0538d650ed to your computer and use it in GitHub Desktop.
Pattern Matching
# 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> 2 = b
2 #huh?
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I guess elixir doesn't support variable matching in the right side?