TypeScript中的标记

时间:2017-06-13 19:55:31

标签: typescript functional-programming monads

我试图想出一种在TypeScript中美化monadic库的方法。虽然monad本身的实现进展顺利,但它的使用看起来像熟悉的回调地狱。

我想知道是否有办法劫持async / await或yield / for..of的现有monadic语法糖,但我必须承认我在连接点时遇到一些麻烦。是否可以在既不是Promise也不是Iterable的东西上使用这些结构,并且与使用react组件组成的continuation monad不同?

1 个答案:

答案 0 :(得分:2)

我的时间有限,但这是一个使用延续monad Cont作为示例的快速小例子



// 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 - 符号 - 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




警告 p>

相关问题