StoutPanda The Bamboo Grove

Elixir & Pattern Matching

Before 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:

1.step(100,1) do |i|
   if (i % 5) == 0 && (i % 3) ==0
    puts 'FizzBuzz'
   elsif (i % 5) == 0
    puts 'Buzz'
   elsif (i % 3) == 0
    puts 'Fizz'
   else
    puts i
   end
end

And now for the pattern matching version in elixir:

fizztest = fn
    (0, 0, _) -> "FizzBuzz"
    (0, _, _) -> "Fizz"
    (_, 0, _) -> "Buzz"
    (_, _, n) -> n
  end

fizzbuzz = fn (n) -> fizztest.(rem(n, 3), rem(n, 5), n) end

IO.inspect Enum.map(1..100, fizzbuzz)

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.