// first: WITHOUT do-notation
const Cont = f => ({
runCont: f,
chain: g =>
Cont(k => f (x => g (x) .runCont (k)))
})
Cont.of = x =>
Cont(k => k (x))
const result = Cont.of (2) .chain (x =>
Cont.of (3) .chain (y =>
Cont.of (x + y)))
result.runCont (console.log)
// 5
现在同样的事情使用 do -notation - do 是JS中的保留关键字,所以我将我的函数命名为 run
// second: WITH do-notation
const run = g => {
const next = x => {
let {value, done} = g.next (x)
return done
? value
: value.chain (next)
}
return next (null)
}
const Cont = f => ({
runCont: f,
chain: g =>
Cont(k => f (x => g (x) .runCont (k)))
})
Cont.of = x =>
Cont(k => k (x))
const result = run (function* () {
let x = yield Cont.of (2)
let y = yield Cont.of (3)
return Cont.of (x + y)
} ())
result.runCont (console.log)
// 5
warning: 你可以使用 async/await 然后你的 Value 卡在Promises内 - 这在大多数情况下可能很烦人 .
1 回答
我是一个使用continuation monad
Cont
作为示例的快速小例子现在同样的事情使用
do
-notation -do
是JS中的保留关键字,所以我将我的函数命名为run
warning: 你可以使用
async/await
然后你的 Value 卡在Promises内 - 这在大多数情况下可能很烦人 .