Pattern Matching Proposal
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:
- On line 1, we define a new function which takes an integer
i
as a parameter and returns astring
. Pretty similar to TypeScript, isn’t it? - On line 2 we declare a
switch
statement, which works similarly to the JavaScriptswitch
. 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 ofi % 3
and the result ofi % 5
…