Elixir & Pattern Matching
18 Oct 2016Before starting with Elixir, I had no functional programming experience. Many of the concepts that are central to using it are very new ideas for me. Prior to this, I only had minimal exposure to lisp when editing a few emacs/spacemacs configuration files.
I’ve only begun to dabble with it, but I am already in infatuated with the power of Pattern Matching. Pattern matching makes things simple. That’s the simplest description I can think of for it.
I had the mind-blowing moment when working with a simple common programming challenge: Fizz Buzz.
Fizz Buzz has of course been done to death on the web, see enterprise Edition Fizz Buzz, but I still can’t get over how simple it was to implement this in elixir.
Fizz Buzz: Requirements: *For numbers 1 through 100, *if the number is divisible by 3 print Fizz; *if the number is divisible by 5 print Buzz; *if the number is divisible by 3 and 5 (15) print FizzBuzz; *else, print the number.
Let’s take a look at the implementation in ruby:
And now for the pattern matching version in elixir:
In elixir, we don’t have to use if statements, or cases. We can define the pattern we are looking for and then return the output we want. We use two anonymous functions, (between the fn & ends) and base the pattern on the return of modulus division (the rem function).
What I find very interesting about pattern matching, is that it comes off very readable and understandable, even when you are not that familiar with the language. Additionally when reviewing the code, there is simply one function call to another, looking for pattern after pattern. It leads me to doing less of this, and leads me to more time spending thinking about what I want to accomplish. While I haven’t built anything noteworthy in it yet, I hope that this pattern continues (slightly more boilerplate code, but much easier to return the project after being away a few days).
For a great introduction to pattern matching and other functional programming concepts, you should check out a series of blog post on medium: So you want to be a functional programmer.