diff --git a/README.md b/README.md index 863df0e..be535c1 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_619 TILs and counting..._ +_620 TILs and counting..._ --- @@ -444,6 +444,7 @@ _619 TILs and counting..._ ### ReasonML - [Exhaustive Pattern Matching Of List Variants](reason/exhaustive-pattern-matching-of-list-variants.md) +- [Helping The Compiler Help Us With Variants](reason/helping-the-compiler-help-us-with-variants.md) - [Inline Component Styles With Reason React](reason/inline-component-styles-with-reason-react.md) - [Multi-Argument Functions As Syntactic Sugar](reason/multi-argument-functions-as-syntactic-sugar.md) - [Pattern Match On Exceptions](reason/pattern-match-on-exceptions.md) diff --git a/reason/helping-the-compiler-help-us-with-variants.md b/reason/helping-the-compiler-help-us-with-variants.md new file mode 100644 index 0000000..cba28f5 --- /dev/null +++ b/reason/helping-the-compiler-help-us-with-variants.md @@ -0,0 +1,38 @@ +# Helping The Compiler Help Us With Variants + +[ReasonML](https://reasonml.github.io/) gives us something called a variant +which is similar to what other language call enums and union types. By +defining a variant, we give the compiler some information about exactly what +values a variable can take on -- its allowed variants. + +Here we define the kinds of roles that users in our system can have as well +as a `user` type for representing individual users: + +```reason +type userType = + | Student + | Teacher + | Admin; + +type user = { role: userType, id: int }; +``` + +And here is how we might use it in some authorization code: + +```reason +let canCreateClasses(u: user) { + switch(u.role) { + | Student => false + | Teacher => true + }; +}; +``` + +We've neglected to include `Admin` in our switch statement. The compiler +will inform us of this with a warning. + +> this pattern-matching is not exhaustive. Here is an example of a value +> that is not matched: Admin + +[source +code](https://reasonml.github.io/en/try.html?reason=C4TwDgpgBArgzhATgFXNAvAKClAPlAZWBgBMIA7YbPKZCAQwGMALJa-AQRIFsBLcgNyZQkWAkRR0UAN5REAewA2EAFxikqSABoovEmv7AoAXyGZlRxvXIBhRA2AQbi+nARwAFDDXwkAShlqOAB3XmAWLwA6BWUA6XZCYjJKSQA+KAAzekUEBLomVgl0dOBEGAhqU0wqgCk4SMV5AHMPK1t7ekdnV3cPWRjVRNIKYB09NQBGACYAZhM-PwEgA)