管道和monad如何在JavaScript中协同工作?

Dan*_*Jr. 8 javascript monads functional-programming pipe

我看过类似的问题和答案,但没有找到直接解决我问题的答案.我在努力理解如何使用MaybeEitherMonads连同管道的功能.我想将函数连接在一起,但我希望管道停止并在任何步骤发生错误时返回错误.我正在尝试在node.js应用程序中实现函数式编程概念,这实际上是我对它们的第一次认真探索,所以没有答案会如此简单以至于侮辱我对这个主题的智慧.

我写了这样的管道函数:

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

module.exports = {arguments.
    pipeAsync: async (...fns) => {
        return await fns.reduce(_pipe)
    }, 
...
Run Code Online (Sandbox Code Playgroud)

我这样称呼它:

    const token = await utils.pipeAsync(makeACall, parseAuthenticatedUser, syncUserWithCore, managejwt.maketoken)(x, y)  
Run Code Online (Sandbox Code Playgroud)

Tha*_*you 18

钩,线和坠子

我不能强调你不会因为你必须学习的所有新术语而陷入困境是多么重要 - 函数式编程是关于函数的 - 也许你唯一需要了解的关于函数的是它允许您使用参数抽象部分程序; 或多个参数(如果需要)(不是)并且由您的语言支持(通常是)

我为什么告诉你这个?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) ...
Run Code Online (Sandbox Code Playgroud)

但是你想写功能程序吧?这对功能程序员来说没有问题.隔离你想要抽象(隐藏)的行为,并简单地将它包装在参数化函数中 - 现在你有了一个函数,继续用函数式编写你的程序......

你做了一段时间之后,你开始注意到图案抽象的-这些模式将作为用例的所有其他的事情(仿函数,applicatives,单子等),你了解后-但保存那些后来 -为现在,功能 ......

下面,我们演示了从左到右的异步函数组合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
Run Code Online (Sandbox Code Playgroud)

发明自己的便利

你可以做一个可变参数compose接受任何数量的功能-也注意到如何让你混合同步,并在同一组合物异步功能-堵右转入的好处.then,它会自动促进非承诺返回值的承诺-

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
Run Code Online (Sandbox Code Playgroud)

工作更聪明,而不是更难

comp并且compose是易于理解的功能,几乎不费力地编写.因为我们使用了内置功能.then,所以所有错误处理的东西都会自动连接起来.您不必担心手动await" try/catch.catch" - 以这种方式编写函数的另一个好处 -

抽象没有羞耻感

现在,这并不是说每次编写抽象都是为了隐藏不好的东西,但它对于各种任务非常有用 - 例如"隐藏"命令式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
Run Code Online (Sandbox Code Playgroud)

但是你想写功能程序吧?这对功能程序员来说没有问题.我们可以创建自己的循环机制,但这次它将使用函数和表达式而不是语句和副作用 - 所有这些都不会牺牲速度,可读性或堆栈安全性.

在这里,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
Run Code Online (Sandbox Code Playgroud)

没有什么是神圣的

记住,你可以做任何你想做的事.没有什么神奇的东西then- 有人,某个地方决定成功.你可以成为某个地方的某个人,只做自己的then- 这then是一种前向组合功能 - 就像Promise.prototype.then它自动应用于thenthen返回值; 我们补充说这不是因为它是一个特别好的主意,而是表明如果我们愿意,我们可以做出这种行为.

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
Run Code Online (Sandbox Code Playgroud)

那是什么语言?

它甚至看起来都不像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
Run Code Online (Sandbox Code Playgroud)

当你明白$,你就会理解所有monad的母亲.记住要专注于力学,并对其运作方式有所了解 ; 不用担心这些条款.

装运它

我们只是使用了名称compcompose我们的本地代码片段,但是当你打包程序时,你应该根据你的具体情况选择有意义的名字 - 参见Bergi对推荐的评论.