i-logoCreated with Sketch.Navigate back to the homepage

Intro to ReasonML Variants

Ian Wilson
March 2nd, 2019 · 3 min read

ReasonML is a super fast, expressive, and functional programming language. Currently, it can be compiled to optimized JavaScript for the web, WebGL/OpenGL for graphics rendering, or even native bytecode.

One of my favorite features of Reason are variant data types. These types allow us to handle enums in a sane way, forcing us to handle all possibilities for a particular scenario. We can define a variant type like this:

1type color =
2 | Red
3 | Blue
4 | White
5 | Black
6 | Grey;

We see that the type color can be represented as this enumeration of different colors. Not too complicated, but not too enlightening either. In JavaScript, we could handle this with an object mapping:

1const COLORS = {
2 RED: 'red',
3 BLUE: 'blue',
4 WHITE: 'white',
5 BLACK: 'black',
6 GREY: 'grey'
7}

I used maps like this all the time in my JavaScript projects, they help a ton when your goal is to keep constants defined in the same place. If you need to update, add, or remove a field, you only need to do so in one location.

If this were the whole story, I would probably decide that a compiled-to-js programming language like Reason is not worth the effort involved when I could just add TypeScript support. After all, so far it has only saved us a tiny amount of code.

Let’s take a look at an example to see how Reason would help us where ordinary JavaScript falls short.

1function getMonthlyPriceForCarColor(color) {
2 switch (color) {
3 case COLORS.RED:
4 return 28
5 case COLORS.BLUE:
6 return 24
7 case COLORS.WHITE:
8 return 20
9 }
10}

This function takes a color (from our convenient colors lookup-map) and returns to us the additional monthly price of getting a Tesla Model S. In other words, getting a red Tesla costs more because it is the best color.

One other thing you might notice is that I did not provide a default case, and as an imperfect programmer, I neglected some of the other colors. JavaScript will not yell at me for this on its own, so I will probably have to find out the hard way that I forgot some of the other cases.

Hopefully QA will catch this bug before my code lands in production. But even if they’re really thorough, I’d still have to make changes and push/review more code. Wouldn’t it be nice if our typechecker could alert us on the fly?

The same function in Reason looks like this:

1let getMonthlyPriceForCarColor = color =>
2 switch(color) {
3 | Red => 28
4 | Blue => 24
5 | White => 20
6 };

First of all there’s less code, which is great, but beside the point. In practice, this function will actually have red squiggly underlines, alerting us that our switch is not exhaustive - it does not cover all of the possibilities or our color variant.

The error message is actually quite helpful when this happens.

Error: Non exhaustive switch statement

Fixing this issue simply requires that you cover the other possibilities.

1let getMonthlyPriceForCarColor = color =>
2 switch(color) {
3 | Red => 28
4 | Blue => 24
5 | White => 20
6 | Black => 0
7 | Grey => 0
8 };

Reason wont let us compile our code if we don’t have a case for each possibility in this function. This is a sampling of the incredibly powerful typesystem we have with Reason.

Variants as Constructors

As I’ve demonstrated so far, variants can be used as enumerations, but they exhibit a power that takes enumeration to a whole new level. Variants can be used as generic constructors that take arguments, allowing developers to further customize applications for their use case.

For example, we can adjust our price (arbitraily) based on the shade of grey or even go as far as to specify a totally arbitrary color somewhere in the RGB scale.

Updating our color type to the following:

1type color =
2 | Red
3 | Blue
4 | White
5 | Black
6 | Grey(float)
7 | Rgb(int, int, int);

Now when we run our function, we can let the customer to pick whatever color they want. To keep make the pricing more reasonable with our already hardcoded values, we’ll allow grey to range from $0 to $20. depending on whatever number given between 0.0 and 1.0.

The Rgb constructor will be the most expensive since we have to create new paint in order to satisfy that requirement. The higher the values of red, blue, and green color, the closer to \$36 it will be.

1let getMonthlyPriceForCarColor = color =>
2 switch(color) {
3 | Red => 28
4 | Blue => 24
5 | White => 20
6 | Black => 0
7 | Grey(pct) => int_of_float(pct *. 20.0)
8 | Rgb(red, green, blue) => {
9 /* completely random calculation. Tesla probably does not do this */
10 let sum = red + green + blue;
11 if (sum > 500) {
12 36
13 } else {
14 32
15 }
16 }
17 };
18
19Js.log(getMonthlyPriceForCarColor(Red)); /* 28 */
20Js.log(getMonthlyPriceForCarColor(Grey(0.64))); /* 12 */
21Js.log(getMonthlyPriceForCarColor(Rgb(150, 210, 67))); /* 32 */
22Js.log(getMonthlyPriceForCarColor(Rgb(150, 210, 167))); /* 36 */

This is pretty neat huh? This example displays the expressive power of a robust type-safe language like Reason.

When we introduce constructor arguments like this, we no longer have an ordinary switch statement that you can find in most programming languages. We call this pattern matching in Reason.

In conjuction with data structures like variants, tuples, and lists, pattern matching creates a readable and concise flow of logic.

Refactor with confidence

The only thing I have yet to do to make this example stronger, is validate the constructor inputs. So to send off this post with a bang, I am going to make some helper functions.

1let validatePercentage = pct =>
2 restrictRangef(pct, 0.0, 1.0);
3
4let validateRgb = (red, blue, green) => {
5 let red = restrictRange(red, 0, 255);
6 let green = restrictRange(green, 0, 255);
7 let blue = restrictRange(blue, 0, 255);
8 (red, blue, green);
9};

These functions validate the required input to the extend that they cut off the values if they are too low or too high. Here are their corresponding restrictRange functions.

1let restrictRange = (number, min, max) =>
2 if (number > max) {
3 max;
4 } else if (number < min) {
5 min;
6 } else {
7 number;
8 };
9
10let restrictRangef = (number, min, max) =>
11 if (number > max) {
12 max;
13 } else if (number < min) {
14 min;
15 } else {
16 number;
17 };

One last thing to note is that we must have separate restrictRange functions for int and float types. By convention, when we have functions that take ints, their float variation will have the same name but with an “f” at the end.

A little extra code here is a small price to pay here when we have superior type coverage.

Finally I can update our getMonthlyPriceForCarColor function with our new helpers:

1let getMonthlyPriceForCarColor = color =>
2 switch (color) {
3 | Red => 28
4 | Blue => 24
5 | White => 20
6 | Black => 0
7 | Grey(pct) => int_of_float(validatePercentage(pct) *. 20.0)
8 | Rgb(red, green, blue) => {
9 let (r, g, b) = validateRgb(red, green, blue);
10 let sum = r + g + b;
11 if (sum > 500) {
12 36
13 } else {
14 32
15 };
16 }
17 };

And thats a wrap

We’ve taken a look at variants and how we can use them with constructor arguments through pattern matching. This is a super powerful feature that you won’t find in just any modern programming language.

When you build an application with complete type safety, you begin to reap the advantages as the size of your project grows and you begin to make refactors. Knowing that your code compiles increases your confidence that you wont break critical or even basic features in production.

More articles from Narative

How a Type System Improves your JavaScript Code

Discover how a type system improves your developer workflow

February 24th, 2019 · 2 min read

ReasonML with React Hooks Tutorial — Building a Pomodoro Timer

Learn Reason React by building a Pomodoro Timer with React hooks

April 15th, 2019 · 6 min read
© 2019 Narative
Link to $https://twitter.com/iwilsonqLink to $https://github.com/iwilsonqLink to $https://instagram.com/iwilsonqLink to $https://www.linkedin.com/iwilsonq/