【问题标题】:Why would one need to use lodash/fp/constant?为什么需要使用 lodash/fp/constant?
【发布时间】:2018-04-10 13:53:57
【问题描述】:

为什么需要使用lodash/fp/constant 中的.constant(value)?我看到其他一些人使用_.constant(true)_.constant(1),但真的不知道它有什么好处。

据我所知.constant(value) 返回一个返回给定value 的函数。我知道它与函数式编程有关,但为什么不直接使用 const VALUE = 1; 呢?

【问题讨论】:

  • 不可变是函数式编程中的一个概念,它为并发提供了一些好处,并使您的函数在数学意义上是纯粹的。 stackoverflow.com/a/279522/2739274

标签: javascript functional-programming lodash


【解决方案1】:

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

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

但没有它实际上会更短:

  Array.from({length: 5}, () => 1);

【讨论】:

  • 对。 _.constant 是一个方便的函数,通常用于构造 iteratees,它总是返回相同的值。
  • 我意识到匿名胖箭头函数语法 not 的一个实例更短或更易读可能是在返回对象文字符号中,例如_.times(7, () => { return {a: 1}})_.times(7, _.constant({a: 1}))
  • @jimmygoggle _.times(7, () => ({ a: 1 }))
【解决方案2】:

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

但是,正如我上面提到的,要了解利用 constant 的高级功能习语,您需要正确理解该范例。

【讨论】:

    【解决方案3】:

    来自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。不错。

    【讨论】:

      猜你喜欢
      • 2015-04-11
      • 2020-10-20
      • 2016-03-10
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      相关资源
      最近更新 更多