1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00

Add Helping The Compiler Help Us With Variants as a reasonml til

This commit is contained in:
jbranchaud
2018-02-18 18:56:21 -06:00
parent c9719514ad
commit 782b311878
2 changed files with 40 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
For a steady stream of TILs from a variety of rocketeers, checkout For a steady stream of TILs from a variety of rocketeers, checkout
[til.hashrocket.com](https://til.hashrocket.com/). [til.hashrocket.com](https://til.hashrocket.com/).
_619 TILs and counting..._ _620 TILs and counting..._
--- ---
@@ -444,6 +444,7 @@ _619 TILs and counting..._
### ReasonML ### ReasonML
- [Exhaustive Pattern Matching Of List Variants](reason/exhaustive-pattern-matching-of-list-variants.md) - [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) - [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) - [Multi-Argument Functions As Syntactic Sugar](reason/multi-argument-functions-as-syntactic-sugar.md)
- [Pattern Match On Exceptions](reason/pattern-match-on-exceptions.md) - [Pattern Match On Exceptions](reason/pattern-match-on-exceptions.md)

View File

@@ -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)