JS函数以相反的顺序组成

时间:2018-06-18 14:05:05

标签: javascript functional-programming function-composition

从简单的功能组合开始

const fa = (x => (x + "a"));
const fb = (x => (x + "b"));
fb(fa('x'))

我玩了,我获得了以下代码片段,它返回'xba'而不是'xab'。

有人可以解释原因吗?

const fa = next => x => next(x + "a");
const fb = next => x => next(x + "b");

console.log(fb(fa(y => y))('x'));

2 个答案:

答案 0 :(得分:4)

让我们打破这个:

const _fa = fa(y => y)
// _fa = x => (y => y)(x + "a")

为避免混淆两个x,请将其命名为x1

// _fa = x1 => (y => y)(x1 + "a")

现在fb将是:

// fb = next => x2 => next(x2 + "b") 

如果我们使用fb(即fa(y => y))致电_fa,我们会将next替换为_fa

_fb = fb(fa(y => y))
// _fb = x2 => (x1 => (y => y)(x1 + "a"))(x2 + "b")

现在让我们使用参数_fb评估x2 = 'x'

// _fb = (x1 => (y => y)(x1 + "a"))("x" + "b")
// _fb = (x1 => (y => y)(x1 + "a"))("xb")

请注意x1 => (y => y)(x1 + "a")如何简化为x1 => x1 + "a"。现在我们有:

// _fb = (x1 => x1 + "a")("xb")

现在让我们用参数(x1 => x1 + "a")

评估这个函数x1 = "xb"
// _fb = "xb" + "a"
// _fb = "xba"

答案 1 :(得分:1)

你可能不知道,但是你正在寻找延续monad!还有thrush combinator



const Cont = someValue => next =>
  next (someValue)

const fa = x =>
  Cont (x + "a")

const fb = x =>
  Cont (x + "b")

fa ("x") (fb) (console.log)
// xab

fb ("x") (fa) (console.log)
// xba

fa ("x") (fa) (fa) (fa) (fb) (console.log)
// xaaaab

fb ("x") (fa) (fb) (fa) (fb) (console.log)
// xbabab




在一个稍微复杂一点的例子中,我们举例说明了liftA2,它采用了二元函数和#34;提升"它进入我们的Cont上下文。现在我们可以使用两个Cont值并将它们与任何普通函数一起使用。



const Cont = someValue => next =>
  next (someValue)
  
const liftA2 = f => mx => my =>
  mx (x =>
    my (y =>
      Cont (f (x, y))))

const mult = (x, y) =>
  x * y
  
const main =
  liftA2 (mult) (Cont (6)) (Cont (7))
  
main (console.log)
// 42

main (x => Cont (x + 1)) (console.log)
// 43