How to Use Elixir Pattern Matched Functions Arguments

Pliny The Elder
Mar 25, 2016 · 1 min read

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!

Rebirth Delivery

Thoughts on Software, Consumer Goods and the World

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store