diff --git a/README.md b/README.md index 7fac441..6ee6893 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/). -_610 TILs and counting..._ +_611 TILs and counting..._ --- @@ -33,6 +33,7 @@ _610 TILs and counting..._ * [PostgreSQL](#postgresql) * [Rails](#rails) * [React](#react) +* [ReasonML](#reasonml) * [Ruby](#ruby) * [tmux](#tmux) * [Unix](#unix) @@ -437,6 +438,10 @@ _610 TILs and counting..._ - [Use A Ref To Autofocus An Input](react/use-a-ref-to-autofocus-an-input.md) - [Visually Select A React Element For Inspection](react/visually-select-a-react-element-for-inspection.md) +### ReasonML + +- [Pattern Match On Exceptions](reason/pattern-match-on-exceptions.md) + ### Ruby - [Are They All True?](ruby/are-they-all-true.md) diff --git a/reason/pattern-match-on-exceptions.md b/reason/pattern-match-on-exceptions.md new file mode 100644 index 0000000..ef8bff2 --- /dev/null +++ b/reason/pattern-match-on-exceptions.md @@ -0,0 +1,33 @@ +# Pattern Match On Exceptions + +[ReasonML](https://reasonml.github.io/) supports [powerful pattern +matching](https://reasonml.github.io/docs/en/pattern-matching.html) through +the `switch` statement. This even includes pattern matching against +exceptions that may arise as a way of catching and handling those +exceptions. + +```reason +let values: list(int) = [1,3,5,7,9]; + +let getValue = (list, index) => { + switch (List.nth(values, index)) { + | value => value + | exception Failure("nth") => 0 + | exception Invalid_argument("List.nth") => 0 + }; +}; + +getValue(values, 0); /* 1 */ +getValue(values, 1); /* 3 */ +getValue(values, 5); /* 0 */ +getValue(values, -1); /* 0 */ +``` + +The [`List.nth` docs](https://reasonml.github.io/api/List.html) detail what +happens in the two kinds of out of bounds scenarios that would raise an +error -- `Failure` and `Invalid_argument`. You can pattern match against +those by declaring the respective cases as exception instances and then +returning the desired values in response. + +[source +code](https://reasonml.github.io/en/try.html?reason=DYUwLgBAbghsCuIDOAuCwCWSwAoMDswBKCAXggG0BGAGgGYaBWGgdhoE4BdAbgChfQkAObgAanERkIOTNhoQCAExAAPEqQB8EAN68IEJAHcMYAMYALaQBksYAHSFzOWAmTylqoiV36APtAkQMi0XRD0If1VTEAAHMAwAe3wIADEYDAQAJxAcACJHXPUtAAZwyJVouMTkgEl8FwxFAH0YTKF4AFsQQjybbAcwc0LgiFL9AF8+Sf4AKSQ7YAShHBEwcVdnQKR5Yq8+OYWllbFAzddtiCo93gPF5dX1xDPEC8Zr26OH09C3CABaK5EbhAA)