代码之家  ›  专栏  ›  技术社区  ›  Huy Vo

为什么需要使用lodash/fp/constant?

  •  4
  • Huy Vo  · 技术社区  · 6 年前

    为什么需要使用 .constant(value) 从…起 lodash/fp/constant ?我看到其他人用 _.constant(true) _.constant(1) 但我真的不知道这有什么好处。

    据我所知 .常数(值) 返回返回给定 value .我知道这与函数式编程有关,但为什么不使用 const VALUE = 1; 相反

    3 回复  |  直到 6 年前
        1
  •  3
  •   Jonas Wilms    6 年前

    一个用例是在创建时填充数组:

      Array.from({length: 5}, _.constant(1))
    

    但如果没有它,它实际上会更短:

      Array.from({length: 5}, () => 1);
    
        2
  •  2
  •   user6445533 user6445533    6 年前

    的使用案例 constant 只有当你理解功能范式时,你才能变得清楚。有了函数式编程,一切都可以用函数来表达。常量也不例外。下面是一个人为的例子:

    const map = f => xs =>
      xs.map(f);
    
    const co = x => y => x;
    
    console.log(
      map(co(0)) ([1,2,3]) // [0,0,0]
    );

    让我们实现一个更复杂的示例。我们想要一个进行两次一元计算的函数(又名动作),但我们只对第二次动作的结果感兴趣。那么,为什么我们首先需要采取第一个行动呢?因为我们对其副作用感兴趣:

    const chain = mx =>
      fm => x => fm(mx(x)) (x);
      
    const co = x => y => x;
    
    const seq = mx => my =>
      chain(mx) (co(my));
      
    const sqr = n =>
      n * n;
      
    // monadic sequence
    
    const z = seq(console.log) (sqr);
    
    // apply it
    
    const r = z(5); // logging 5 is the observed effect
    
    console.log("return value:", r); // logs the return value 25

    通常是一篇带有 console.log 将导致错误: add(console.log(5)) (5) 收益率 NaN .但我们的实际构成 add(co(sqr) (console.log(5)) (5) 和收益率 25 根据需要。

    然而,正如我上面提到的,要理解高级功能性习语 常数 你需要正确理解范式。

        3
  •  1
  •   Brian Kung    6 年前

    从…起 https://github.com/jashkenas/underscore/issues/402#issuecomment-3112193 :

    // api: object.position = function(time) { return coords }
    circle.position = _.constant( [10, 10] )
    
    // api: image.fill( function(x, y) { return color })
    image.fill( _.constant( black ) );
    

    因此,主要用于将常量传递给期望函数的API。美好的