【问题标题】:How do pipes and monads work together in JavaScript?管道和单子如何在 JavaScript 中协同工作?
【发布时间】:2018-04-05 15:38:04
【问题描述】:

我查看了类似的问题和答案,但没有找到直接解决我问题的答案。我很难理解如何将Maybe 或Either 或Monads 与管道功能结合使用。我想将函数连接在一起,但是如果在任何步骤发生错误,我希望管道停止并返回错误。我正在尝试在 node.js 应用程序中实现函数式编程概念,这确实是我对两者的第一次认真探索,所以没有任何答案会如此简单,以至于侮辱我在这个主题上的智慧。

我写了一个这样的管道函数:

const _pipe = (f, g) => async (...args) => await g( await f(...args))

module.exports = {arguments.
    pipeAsync: async (...fns) => {
        return await fns.reduce(_pipe)
    }, 
...

我这样称呼它:

    const token = await utils.pipeAsync(makeACall, parseAuthenticatedUser, syncUserWithCore, managejwt.maketoken)(x, y)  

【问题讨论】:

  • 没有 "pipes" 也没有 Monads
  • 你要找的是monadic chain,而不是普通的函数组合。 await 只对承诺有帮助。
  • 第 3 行的 arguments. 是错字还是我从未见过的语法?

标签: javascript functional-programming pipe monads


【解决方案1】:

钩、线和坠子

我不能强调不要被所有你必须学习的新术语所困扰——函数式编程是关于函数的——这可能是唯一的事情您需要了解的功能是它允许您使用参数抽象部分程序;或多个参数(如果需要(不是)并且您的语言支持(通常是))

我为什么要告诉你这个?好吧,JavaScript 已经有一个非常好的 API 用于使用内置的异步函数排序,Promise.prototype.then

// never reinvent the wheel
const _pipe = (f, g) => async (...args) => await g( await f(...args))
myPromise .then (f) .then (g) .then (h) ...

但是您想编写函数式程序,对吗?这对函数式程序员来说没有问题。隔离您想要抽象(隐藏)的行为,并将其简单地包装在一个参数化的 function 中——现在您有了一个函数,继续以函数式风格编写您的程序...

在您这样做一段时间后,您开始注意到抽象的模式——这些模式将用作您学习的所有其他事物(函子、应用程序、monad 等)的用例关于稍后 - 但保存那些稍后 - 现在,函数 ...

下面,我们通过comp 演示异步函数的从左到右组合。就本程序而言,delay 被包含为 Promises 创建者,sq 和 add1 是示例异步函数 -

const delay = (ms, x) =>
  new Promise (r => setTimeout (r, ms, x))

const sq = async x =>
  delay (1000, x * x)
  
const add1 = async x =>
  delay (1000, x + 1)

// just make a function  
const comp = (f, g) =>
  // abstract away the sickness
  x => f (x) .then (g)

// resume functional programming  
const main =
  comp (sq, add1)

// print promise to console for demo
const demo = p =>
  p .then (console.log, console.error)

demo (main (10))
// 2 seconds later...
// 101

创造自己的便利

您可以创建一个可变参数 compose 来接受任意数量的函数 - 还要注意这如何让您在同一组合中混合同步 和 异步函数 - 插入 @987654332 的好处@,它会自动将非 Promise 返回值提升为 Promise -

const delay = (ms, x) =>
  new Promise (r => setTimeout (r, ms, x))

const sq = async x =>
  delay (1000, x * x)
  
const add1 = async x =>
  delay (1000, x + 1)

// make all sorts of functions
const effect = f => x =>
  ( f (x), x )

// invent your own convenience
const log =
  effect (console.log)
  
const comp = (f, g) =>
  x => f (x) .then (g)

const compose = (...fs) =>
  fs .reduce (comp, x => Promise .resolve (x))
  
// your ritual is complete
const main =
  compose (log, add1, log, sq, log, add1, log, sq)

// print promise to console for demo
const demo = p =>
  p .then (console.log, console.error)

demo (main (10))
// 10
// 1 second later ...
// 11
// 1 second later ...
// 121
// 1 second later ...
// 122
// 1 second later ...
// 14884

工作更聪明,而不是更努力

comp 和 compose 是易于理解的函数,几乎不费吹灰之力就可以编写。因为我们使用了内置的.then,所以所有错误处理的东西都会自动为我们连接起来。您不必担心手动 await'ing 或 try/catch 或 .catch'ing - 但是另一个以这种方式编写我们的函数的好处 -

抽象并不羞耻

现在,这并不是说每次您编写抽象都是为了隐藏某些东西不好,但它对于各种任务可能非常有用 - 例如“隐藏”命令式while -

const fibseq = n => // a counter, n
{ let seq = []      // the sequence we will generate
  let a = 0         // the first value in the sequence
  let b = 1         // the second value in the sequence
  while (n > 0)     // when the counter is above zero
  { n = n - 1             // decrement the counter
    seq = [ ...seq, a ]   // update the sequence
    a = a + b             // update the first value
    b = a - b             // update the second value
  }
  return seq        // return the final sequence
}

console .time ('while')
console .log (fibseq (500))
console .timeEnd ('while')
// [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...  ]
// while: 3ms

但是您想编写函数式程序,对吗?这对函数式程序员来说没有问题。我们可以创建自己的循环机制,但这次它将使用函数和表达式而不是语句和副作用——所有这些都不会牺牲速度、可读性或stack safety。

在这里,loop 使用我们的 recur 值容器不断地应用一个函数。当函数返回非recur值时,计算完成,返回最终值。 fibseq 是一个纯函数表达式,具有无限递归。两个程序都在大约 3 毫秒内计算出结果。不要忘记检查答案是否匹配:D

const recur = (...values) =>
  ({ recur, values })

// break the rules sometimes; reinvent a better wheel
const loop = f =>
{ let acc = f ()
  while (acc && acc.recur === recur)
    acc = f (...acc.values)
  return acc
}
      
const fibseq = x =>
  loop               // start a loop with vars
    ( ( n = x        // a counter, n, starting at x
      , seq = []     // seq, the sequence we will generate
      , a = 0        // first value of the sequence
      , b = 1        // second value of the sequence
      ) =>
        n === 0      // once our counter reaches zero
          ? seq      // return the sequence
          : recur    // otherwise recur with updated vars
              ( n - 1          // the new counter
              , [ ...seq, a ]  // the new sequence
              , b              // the new first value
              , a + b          // the new second value
              )
    )

console.time ('loop/recur')
console.log (fibseq (500))
console.timeEnd ('loop/recur')
// [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...  ]
// loop/recur: 3ms

没有什么是神圣的

请记住,您可以为所欲为。 then 没有什么神奇之处——有人在某个地方决定成功。你可以在某个地方成为某个人,然后创建自己的then——这里的then是一种前向组合函数——就像Promise.prototype.then一样,它会自动将then应用于非then的返回值;我们添加这个不是因为它是一个特别好的主意,而是为了表明我们可以根据需要做出这种行为。

const then = x =>
  x && x.then === then
    ? x
    : Object .assign
        ( f => then (f (x))
        , { then }
        )
  
const sq = x =>
  then (x * x)
  
const add1 = x =>
  x + 1
  
const effect = f => x =>
  ( f (x), x )
  
const log =
  effect (console.log)
  
then (10) (log) (sq) (log) (add1) (add1) (add1) (log)
// 10
// 100
// 101

sq (2) (sq) (sq) (sq) (log)
// 65536

那是什么语言?

它甚至不再像 JavaScript,但谁在乎呢?这是你的程序,你决定你想要它的样子。一种好的语言不会妨碍您并迫使您以任何特定的风格编写程序;功能或其他方面。

它实际上是 JavaScript,只是不受对其能力表达的误解的束缚 -

const $ = x => k =>
  $ (k (x))
  
const add = x => y =>
  x + y

const mult = x => y =>
  x * y
  
$ (1)           // 1
  (add (2))     // + 2 = 3
  (mult (6))    // * 6 = 18
  (console.log) // 18
  
$ (7)            // 7
  (add (1))      // + 1 = 8
  (mult (8))     // * 8 = 64
  (mult (2))     // * 2 = 128
  (mult (2))     // * 2 = 256
  (console.log)  // 256

当您了解$ 时,您将了解the mother of all monads。记住要专注于机制并了解它是如何工作的;不用担心条款。

发货

我们只是在本地 sn-ps 中使用了名称 comp 和 compose,但是当您打包程序时,您应该根据您的特定上下文选择有意义的名称 - 请参阅 Bergi 的评论以获取建议。

【讨论】:

  • 你应该称它为compAsync 以区别于通常的函数组合。甚至compKleisli,如果你想变得花哨的话:-)
  • @Bergi,哦,我的意思是要提一下将其导出为不同的名称 - 感谢您的评论。我会稍作修改。
  • 感谢您的回答。有些事情还不清楚。请不要陷入异步/等待的事情。我把它放在那里是因为我需要编写的几个函数是异步设计的,除非它一直是异步的,否则它将无法工作。我更喜欢这种语法,因为 1)我从 C# 熟悉它,2 它是 nodejs 中最新的方法。如果我需要用“then”来做,我会做出改变。我相信我混合了太多我不明白的东西。如果我们去掉了异步,那么你将如何在错误时中断管道?
  • async/await 是 Promise.prototype.then在幕后 - 它只是一个不同的语法 - 我们可以使用await 但重点是表明没有必要使用这种重型机械;当我们用一个简单的f(x).then(g) 得到我们想要的 *exact 行为时,这有点过头了
  • .... (cont.):换一种方式是绝对可以的,但是你的理由不好; 1)其他语言(C#)的语法对 JS 能够表达的内容没有影响; 2) 其他人如何选择编写他们的程序,“nodejs 中的最新方式”,对您的偏好没有直接影响——latest 也不意味着 best——当 CoffeeScript 是*最新的方式时,许多人将非常好的 JavaScript 程序库翻译成一种死胡同。
【解决方案2】:

naomik 的回答很有趣,但她似乎并没有真正抽空回答你的问题。

简短的回答是您的_pipe 函数可以很好地传播错误。并在抛出错误时立即停止运行函数。

问题在于您的 pipeAsync 函数,您有正确的想法,但您不必要地让它返回一个函数的 promise 而不是函数。

这就是为什么你不能这样做,因为它每次都会抛出一个错误:

const result = await pipeAsync(func1, func2)(a, b);

为了在当前状态下使用pipeAsync,您需要两个awaits:一个获取pipeAsync 的结果,一个获取调用该结果的结果:

const result = await (await pipeAsync(func1, func2))(a, b);

解决方案

从pipeAsync的定义中去掉不必要的async和await。组合一系列函数的行为,甚至是异步函数,都不是异步操作:

module.exports = {
    pipeAsync: (...fns) => fns.reduce(_pipe),

一旦你这样做了,一切都很好:

const _pipe = (f, g) => async(...args) => await g(await f(...args))
const pipeAsync = (...fns) => fns.reduce(_pipe);

const makeACall = async(a, b) => a + b;
const parseAuthenticatedUser = async(x) => x * 2;
const syncUserWithCore = async(x) => {
  throw new Error("NOOOOOO!!!!");
};
const makeToken = async(x) => x - 3;

(async() => {
  const x = 9;
  const y = 7;

  try {
    // works up to parseAuthenticatedUser and completes successfully
    const token1 = await pipeAsync(
      makeACall,
      parseAuthenticatedUser
    )(x, y);
    console.log(token1);

    // throws at syncUserWithCore
    const token2 = await pipeAsync(
      makeACall,
      parseAuthenticatedUser,
      syncUserWithCore,
      makeToken
    )(x, y);
    console.log(token2);
  } catch (e) {
    console.error(e);
  }
})();

这也可以完全不用async来写:

const _pipe = (f, g) => (...args) => Promise.resolve().then(() => f(...args)).then(g);
const pipeAsync = (...fns) => fns.reduce(_pipe);

const makeACall = (a, b) => Promise.resolve(a + b);
const parseAuthenticatedUser = (x) => Promise.resolve(x * 2);
const syncUserWithCore = (x) => {
  throw new Error("NOOOOOO!!!!");
};
const makeToken = (x) => Promise.resolve(x - 3);

const x = 9;
const y = 7;

// works up to parseAuthenticatedUser and completes successfully
pipeAsync(
  makeACall,
  parseAuthenticatedUser
)(x, y).then(r => console.log(r), e => console.error(e));

// throws at syncUserWithCore
pipeAsync(
  makeACall,
  parseAuthenticatedUser,
  syncUserWithCore,
  makeToken
)(x, y).then(r => console.log(r), e => console.error(e))

【讨论】:

    猜你喜欢
    • 2012-11-30
    • 1970-01-01
    • 2014-12-19
    • 2018-01-16
    • 2015-08-17
    • 1970-01-01
    • 2021-12-09
    • 2019-04-21
    • 2014-08-05
    相关资源
    最近更新 更多