Understanding Pattern Matching

Hello, channel,

I am learning the pattern matching in elixir. if I define a variable with boolean value and pattern match using atom like follow, matches correctly

bool = true
:true = bool

but if I try the match string with the atom, getting pattern match error

name = "foobar"
:foobar = name

MatchError) no match of right hand side value: "foobar"
(stdlib) erl_eval.erl:453: :erl_eval.expr/5
(iex) lib/iex/evaluator.ex:249: IEx.Evaluator.handle_eval/5
(iex) lib/iex/evaluator.ex:229: IEx.Evaluator.do_eval/3
(iex) lib/iex/evaluator.ex:207: IEx.Evaluator.eval/3
(iex) lib/iex/evaluator.ex:94: IEx.Evaluator.loop/1
(iex) lib/iex/evaluator.ex:24: IEx.Evaluator.init/

The value true is syntactic sugar for :true, i.e. the true value is actually an atom. However strings and atoms are fundamentally different types and therefore will never match.

iex(1)> is_atom(true)
true
iex(2)> is_atom(:true)
true
iex(3)> is_binary(true)
false
iex(4)> is_binary(:true)
false
iex(5)> is_binary("foobar")
true
iex(6)> is_atom("foobar")  
false
iex(7)> is_atom(false)   
true
iex(8)> is_atom(:false)
true
iex(9)> is_atom(nil)   
true
iex(10)> is_atom(:nil)
true
iex(11)>
5 Likes

Thanks, So match operator will fail based on underlying datatype.

    [] = {}

** (MatchError) no match of right hand side value: {}
(stdlib) erl_eval.erl:453: :erl_eval.expr/5
(iex) lib/iex/evaluator.ex:249: IEx.Evaluator.handle_eval/5
(iex) lib/iex/evaluator.ex:229: IEx.Evaluator.do_eval/3
(iex) lib/iex/evaluator.ex:207: IEx.Evaluator.eval/3
(iex) lib/iex/evaluator.ex:94: IEx.Evaluator.loop/1
(iex) lib/iex/evaluator.ex:24: IEx.Evaluator.init/4
iex(5)> 1 = β€œ1”
** (MatchError) no match of right hand side value: β€œ1”
(stdlib) erl_eval.erl:453: :erl_eval.expr/5
(iex) lib/iex/evaluator.ex:249: IEx.Evaluator.handle_eval/5
(iex) lib/iex/evaluator.ex:229: IEx.Evaluator.do_eval/3
(iex) lib/iex/evaluator.ex:207: IEx.Evaluator.eval/3
(iex) lib/iex/evaluator.ex:94: IEx.Evaluator.loop/1
(iex) lib/iex/evaluator.ex:24: IEx.Evaluator.init/4

you can’t compare apples with oranges, you can only pattern match on the same datatype for example [] will pattern match on lists and {} will only pattern match on tuples,

3 Likes