Last active
August 29, 2015 14:27
-
-
Save holoed/a96cdceba954805d750b to your computer and use it in GitHub Desktop.
JavaScript Async function compositions through the Continuation Monad
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
| // unit :: a -> m a | |
| const unit = x => c => c (x) | |
| // bind :: m a -> (a -> m b) -> m b | |
| const bind = m => f => c => m (x => f(x)(c)) | |
| // map :: ma -> (a -> b) -> m b | |
| const map = m => f => bind (m) (x => unit(f(x))) | |
| // foldr :: (a -> b -> b) -> b -> [a] -> b | |
| const foldr = f => acc => xs => (xs.length == 0) ? acc : f(xs[0]) (foldr(f)(acc)(xs.slice(1))) | |
| // flip :: (a -> b -> c) -> (b -> a -> c) | |
| const flip = f => x => y => f (y) (x) | |
| // sequence :: m b -> [a -> m b] -> m b | |
| const sequence = acc => ms => foldr (flip (bind)) (acc) (ms) | |
| // Sample usage | |
| const f = x => unit(x + 3) | |
| const g = x => unit(x * 2) | |
| const h = x => unit("Number " + x) | |
| const k = sequence (unit(4)) ([h, g, f]) | |
| k(x => console.log("result: " + x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment