How to Use Elixir Pattern Matched Functions Arguments

Pliny The Elder
Rebirth Delivery
Published in
1 min readMar 25, 2016

One of the coolest thing about elixir is pattern matching in functions.

It eliminates dumb forking, the canonical example being fibonacci. In ruby it looks like this:

So much forking! That three line method has literally got three different code paths through it. In elixir we can pattern match in function calls allowing us to create functions with less branching.

Each function doesn’t have any branches and is easier to reason about. Personally I have fib. It never has any relevance in my life, so what does this mean practically?

While making Rebirth I needed to add a subscription to a user. I needed to do something different depending on whether or not the user already has a subscription. We can try something like

The problem being we actually need to use the user in the case the user has no subscription. SOLUTION: You can assign variables in the function definition.

And now we can actually use the user inside the first function where we need them!

--

--