Pattern Matching Proposal

Michele Riva
openmind
Published in
4 min readMay 27, 2019

--

If you’re coming from a functional programming language such as Elixir, Haskell or ReasonML, you may know how frustrating is to switch to a language which does not support pattern matching natively.

Once you start to approach problem using pattern matching, you’ll never go back to the messy if/else if/ else statements!

Let’s see what I’m talking about, coding the famous FizzBuzz interview question in both ReasonML and plain JavaScript:

So as you can see in the ReasonML implementation above, we’re using a switch statement which pattern matches agains a tuple, returning the desired output on specific conditions.
I’ll explain for you how does it work, just in case you’re not familiar with ReasonML:

  1. On line 1, we define a new function which takes an integer i as a parameter and returns a string. Pretty similar to TypeScript, isn’t it?
  2. On line 2 we declare a switch statement, which works similarly to the JavaScript switch. In that case, we’re switching against a tuple, which is a ReasonML immutable, ordered and fix-sized data structure that contains two integers: the result of i % 3 and the result of i % 5

--

--