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

Add Defining Variants With Constructor Arguments as a reasonml til

This commit is contained in:
jbranchaud
2018-02-19 13:08:54 -06:00
parent 782b311878
commit d7d73472f2
2 changed files with 41 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
[til.hashrocket.com](https://til.hashrocket.com/).
_620 TILs and counting..._
_621 TILs and counting..._
---
@@ -443,6 +443,7 @@ _620 TILs and counting..._
### ReasonML
- [Defining Variants With Constructor Arguments](reason/defining-variants-with-constructor-arguments.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)

View File

@@ -0,0 +1,39 @@
# Defining Variants With Constructor Arguments
In [Helping The Compiler Help Us With
Variants](https://github.com/jbranchaud/til/blob/master/reason/helping-the-compiler-help-us-with-variants.md),
I introduced the concept of variants with a basic example of how to define
and use one. The fun doesn't stop there.
We can take variants a step further by defining them with constructor
arguments.
```reason
type listActions =
| Length
| Nth(int);
```
The second variant is defined such that it is paired with some extra data --
a single `int` argument.
Here is how we use that variant in our code:
```reason
let performListAction = (l: list(int), action: listActions) => {
switch(action) {
| Length => List.length(l)
| Nth(n) => List.nth(l, n)
}
};
performListAction([7,8,9], Nth(1)); /* 8 */
performListAction([1,2,3], Length); /* 3 */
```
Our switch statement not only matches on that variant, but it makes the
`int` argument available as a value we can consume in that step of the
switch.
[source
code](https://reasonml.github.io/en/try.html?reason=C4TwDgpgBANglgZ2AQQMbDgewHYKgXgCgooAfKAGQmwHNgALYsqAOQYAo5tgBKAbkKEYEYFEgAnAGaZxAWwqIU6LNgJR2MAFyxFnbjwA0UAIbKc2+EjQYcCHgQB8UAN5MEAdzjBU9dqZvY9q4k5FS0DI6UigB0wuG+MDxM5Gy+gZEKSNHcCUaBTAC+hAUChABSCLGYNOwS0nKZSgHsANoA7AYAHAYAnAC6RqnsAIw8YwIVVTV1MvKK1iqtwwYATAYAzAOU1HT040A)