Last active
October 23, 2015 07:21
-
-
Save bangedorrunt/b80861ff5eabc582f7fa to your computer and use it in GitHub Desktop.
Functional JavaScript
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
| // Functors apply a function to a wrapped value and then return a wrapped value | |
| // Functors are chainable | |
| // Functor::(a -> b) -> f(a) -> f(b) | |
| class Wrapper { | |
| constructor(val) { | |
| console.log('Created a wrapped value ' + val); | |
| this.val = val; | |
| } | |
| // Functor's `fmap` in Haskell | |
| map(func) { | |
| return new Wrapper(func(this.val)); | |
| } | |
| // Monad's `return` in Haskell | |
| static of(val) { | |
| return new Wrapper(val); | |
| } | |
| } | |
| let value = 'Hello World!'; | |
| // Functor | |
| Wrapper.of(value).map(_.words).map(_.size); |
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
| // Monads apply a function that returns a wrapped values to a wrapped value | |
| // and then return a wrapped value | |
| // Monads are chainable | |
| class Wrapper { | |
| constructor(val) { | |
| console.log('Created a wrapped value ' + val); | |
| this.val = val; | |
| } | |
| // Functor's `fmap` in Haskell | |
| map(func) { | |
| return new Wrapper(func(this.val)); | |
| } | |
| // Monad's `>>=` (pronounced bind) in Haskell | |
| flatMap(func) { | |
| return func(this.val); | |
| } | |
| // Monad's `return` in Haskell | |
| static of(val) { | |
| return new Wrapper(val); | |
| } | |
| } | |
| let value = 2; | |
| // Monad | |
| Wrapper.of(value).flatMap(function(x){ return Wrapper.of(x+2)}).flatMap(function(x) {return Wrapper.of(x*-1)}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment