【问题标题】:JS functions composed in the opposite orderJS函数以相反的顺序组成
【发布时间】:2018-06-18 14:05:04
【问题描述】:

从一个简单的函数组合开始

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

我玩了一下,得到了以下代码 sn-p,它返回 'xba' 而不是 'xab'。

谁能解释一下原因?

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

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

【问题讨论】:

  • 你预计会发生什么?
  • 我期待'xab'。但我不知道执行顺序是什么或到底发生了什么。所以我想了解为什么'xba'是结果
  • fa 创建一个附加"a" 的函数。这个函数被传递给fb,它追加"b",然后调用传递的函数(它追加"a")。

标签: javascript functional-programming function-composition


【解决方案1】:

让我们分解一下:

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") 

如果我们用fa(y => y)(即_fa)调用fb,我们用_fa替换next

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

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

// _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 = "xb" 评估这个函数(x1 => x1 + "a")

// _fb = "xb" + "a"
// _fb = "xba"

【讨论】:

    【解决方案2】:

    您可能不知道,但您正在查看 continuation 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,它接受一个二进制函数并将其“提升”到我们的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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多