Variants and Pattern Matching Variants using switch in Reason

Nik Graf
InstructorNik Graf

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

Variants are known as tagged unions in Computer Science. They allow us to express multiple options that are exclusive, as a data structure. A concept that isn't available in too many programming languages and yet such a powerful concept.

We explore how to create variants and constructors in ReasonML and briefly touch on how to pattern match them to extract data.

Instructor: [00:00] Variants allow us to express module options that are exclusive as a data structure. Let's create a variant answer referring to a set of so-called constructors, or also called tags, each of them separated by the pipe character. Constructors must be capitalized.

[00:18] We can bind these constructors using the let keyword like any other value. For example, Reason's great. Yes. Is it raining? Maybe. This data structure allows us to express this or that with as many options as we want. In computer science, this is called tagged unions.

[00:40] Variants' usefulness is mostly coming along with the switch expression. It allows us to check every possible case of a variant. We create a let binding message, open a switch expression for Reason is great, then, we enumerate every variant constructor, each followed by an arrow and the corresponding case. So far, so good.

[01:11] We could have achieved the same result with an if/else expression, but when using variants in combination with switch, we get a rich amount of type system assistants. For example, the compiler will give us a type error if we forget to cover a case. It even points out which cases are missing. In addition, the compiler warns us if two cases are redundant.

[01:35] There is more to variants, though. Each of its constructors can hold extra data. Let's create a variant item for an App Store notes, and to-do's. Note can only include the text, while a to-do has text, as well as a Boolean indicating if it's done or not.

[02:03] We can call the to-do constructor with these two arguments. In our case, we want to redesign a website and set it to false. To leverage this in a switch expression, we can pattern match on a constructor's parameters, and extract them when needed.

[02:20] To do so, we can use destructuring. This way, we can give the parameters' names and use them each after the arrow. While we can give the names, we don't necessarily have to. We also can match against exact values of the constructor.

[02:41] Here, we add a pattern that matches exactly against redesigned website with the Boolean set to false.