Skip to content

Instantly share code, notes, and snippets.

@redice
Last active August 29, 2015 14:08
Show Gist options
  • Save redice/f25a57871300dcafc842 to your computer and use it in GitHub Desktop.
Save redice/f25a57871300dcafc842 to your computer and use it in GitHub Desktop.
Prove promise as a monad
# Promise = require 'promise'
##
compare2Promise = (title, pA, pB) ->
valueA = null
valueB = null
pA.then (value) ->
valueA = value
pB.then (value) ->
valueB = value
Promise.all [pA, pB]
.then ->
console.log "==> #{title}"
console.log "value of A: #{valueA}"
console.log "value of B: #{valueB}"
console.log "equals is #{if valueA is valueB then 'true' else 'false'}"
###
The first law
M(mResult(x), mf) = mf(x)
###
promiseMonad = (mv, mf) ->
Promise::then.call mv, mf
x = "monad example"
# mResult is a function as Promise.resolve
promiseMonad.mResult = Promise.resolve.bind(Promise)
mf = (value) ->
new Promise (resolved, rejected) ->
resolved value + " monadF"
result1 = promiseMonad promiseMonad.mResult(x), mf
result2 = mf x
compare2Promise "First Law:", result1, result2
###
The second law
M(mv, mResult) = mv
###
mv = Promise.resolve [4]
result1 = promiseMonad mv, promiseMonad.mResult
result2 = mv
compare2Promise "Second Law:", result1, result2
###
The third law
M(M(mv, mf), mg)) = M(mv, function(x){return M(mf(x), mg)})
###
mg = (value) ->
new Promise (resolved, rejected) ->
resolved value + " monadG"
result1 = promiseMonad promiseMonad(mv, mf), mg
result2 = Promise::then.call mv, (x) ->
Promise::then.call (mf x), mg
compare2Promise "Third Law:", result1, result2
@redice
Copy link
Author

redice commented Nov 3, 2014

According to Functional JavaScript(http://functionaljavascript.blogspot.tw/2013/07/monads.html) posted by Santosh Rajan, I write codes to prove Promise as a kind of monad.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment