Parameter pattern matching

Can someone explain to me how parameter pattern matching works exactly?

def foo({a,b}) do

Pattern matching that happens: {a,b} = {1,2}

def equal(a,a), do: true

Pattern matching that happens?

I was wondering because if it happens like a=1 and then a=1 then equal(1,2) would have matched fine because a=1 and then a=2 is totally legal.

a=1 and then a=2 is totally legal

It is not actually. The assignment happens once (a=1), and a=2 would mean 1=2 which doesn’t match.

1 Like

It’s explained here:

If a variable is mentioned more than once in a pattern, all references should bind to the same pattern:
iex> {x, x} = {1, 1}
{1, 1}
iex> {x, x} = {1, 2}
** (MatchError) no match of right hand side value: {1, 2}

I’m thinking in terms of

iex(116)> a = 1
iex(117)> a = 1

So am i right to say that for parameter pattern matching, the parameters are taken in as a tuple and tuple pattern matching happens

def equal(a,a), do: true

Patter n matching that happens: {a,a} = {1,1}
Hence {a,b} = {1,2} matching fails

Not really, because this happens even with a single parameter.

def equal(%{x: a, y: a}), do: true

will return true for %{x: 1, y: 1} and raise for %{x: 1, y: 2}.

For your example its a function of arity 1, i am trying to find out what actually happens for function with arity more than 1

During compilation

def equal(a,a), do: true

is basically rewritten to

def equal(a,b) when a === b, do: true

Both these functions compile to the exact same bytecode.