如何为monad实现通用提升功能?

bob*_*bob 4 javascript monads functional-programming lifting

我有很多了解Arity的电梯功能:

const chain = f => xs =>
  xs.reduce((acc, x) => acc.concat(f(x)), []);

const of = x => [x];

const add = (x, y) => x + y;

const liftM2 = (chain, of) => f => m1 => m2 =>
  chain(x => chain(y => of(f(x, y))) (m2)) (m1);

console.log(liftM2(chain, of) (add) ([2]) ([3])); // [5]
Run Code Online (Sandbox Code Playgroud)

是否可以实现相应的通用举升功能?

const liftM = (chain, of) => f => (...ms) => ...
Run Code Online (Sandbox Code Playgroud)

我猜这是一种递归算法,但是我无法将其包裹住。

Ber*_*rgi 5

是的,您可以在上递归地执行此操作ms,但我想弃牌比较合适:

const lift = (chain, of) => f => (...ms) =>
  ms.reduceRight((acc, m) =>
    (...xs) => chain(x => acc(...xs, x))(m)
  , (...xs) => of(f(...xs))
  )()
Run Code Online (Sandbox Code Playgroud)