Pattern Matching

Oskar Szrajer,  Mar 24, 2017

Last time I wrote about writing more functional code in ruby. But except that we can take a lot more from functional languages, for example Pattern Matching.

It’s not my intention to write here what pattern matching is, most of us knows it or can check in Wikipedia for example. I want to present how to use it in ruby and how these forgotten techniques can simplify or code.

A while ago my friend - Michał Kwiatkowski - present on our local ruby community meetup - TRUG - a talk “Języki funkcyjne: czego jeszcze mogą nas nauczyć?”. I want to summarize what he teaches all of us.

He presents a functional solution for one of programming exercise often used during recruitment process - FizzBuzz.

The rules are simple. Your task is to generate (and print on screen) a series of numbers from 1 to 100 and replace every number divided by 3 to Fizz, by 5 to Buzz and by 3 and 5 to FizzBuzz. Almost everybody will write a code similar to this one:

(1..100).each do |i|
  if i%3 == 0 && i%5 == 0
    p 'FizzBuzz'
  elsif i%3 == 0
    p 'Fizz'
  elsif i%5 == 0
    p 'Buzz'
    p i

There is nothing wrong with this code, all tests pass so it works. Of course, you can polish it more and squeeze to only 3 conditions, or replace by other conditional technique, like case, but it still by the same in general. But what if someone asks us to write the same function without using any conditions. Your first thought will be - it’s impossible!. Here’s how pattern matching will help us:

(1..100).each do |i|
    [true, true]    =>  "FizzBuzz",
    [true, false]   =>  "Fizz",
    [false, true]   =>  "Buzz",
    [false, false]  =>  i
  }[[i%3 == 0, i%5 == 0]])

The example above use simple hash and rule that allows a key of the hash to be anything (almost). So simple and so powerful and at the same time so hard to imagine for us - OOP developers. Hope this lesson will show you how important is to learn FP and how its techniques can simplify our daily code.

Oskar Szrajer

Oskar is a full-stack developer & software architect. He’s driven by contributing to beautiful user - and customer-driven applications and will dive into any aspect of an application, in any technology, if it will help serve a well-fitting end result.

Published on:

Mar 24, 2017