Created
August 2, 2018 05:05
-
-
Save pfgray/f8f39eb293037783a05dbf39ea548829 to your computer and use it in GitHub Desktop.
Do syntax for js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // nested chaining is a common occurence for monads: | |
| // type Maybe = Just(a) | Nothing | |
| Just(5) | |
| .chain(num => Just(num * 2) | |
| .chain(num2 => Just(num2 + 3) | |
| .map(num3 => ({num, num2, num3})) | |
| ) | |
| ) | |
| // this yields: | |
| // Just({ | |
| // num: 5, | |
| // num2: 10, | |
| // num3: 13 | |
| // }) | |
| // To avoid nesting, we can implement a function Do, which takes | |
| // instances of Monads, and an arbitrary list of functions with | |
| // increasing parameter count, and chains them automatically: | |
| Do( | |
| Just(5), | |
| (num) => Just(num * 2), | |
| (num, num2) => Just(num2 + 3), | |
| (num, num2, num3) => ({num, num2, num3}) | |
| ) | |
| // which yields: | |
| // Just({ | |
| // num: 5, | |
| // num2: 10, | |
| // num3: 13 | |
| // }) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment