Skip to content

Instantly share code, notes, and snippets.

@holoed
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save holoed/a96cdceba954805d750b to your computer and use it in GitHub Desktop.

Select an option

Save holoed/a96cdceba954805d750b to your computer and use it in GitHub Desktop.
JavaScript Async function compositions through the Continuation Monad
// 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