Javascript 为什么需要使用lodash/fp/constant?
为什么需要从Javascript 为什么需要使用lodash/fp/constant?,javascript,functional-programming,lodash,Javascript,Functional Programming,Lodash,为什么需要从lodash/fp/constant使用.constant(value)?我看到其他一些人使用.constant(true)或.constant(1),但并不知道它的好处是什么 据我所知,常量(值)返回一个函数,该函数返回给定的值。我知道它与函数式编程有关,但为什么不直接使用const VALUE=1相反?一个用例是在创建时填充数组: Array.from({length: 5}, _.constant(1)) 但如果没有它,它实际上会更短: Array.from({len
lodash/fp/constant
使用.constant(value)
?我看到其他一些人使用.constant(true)
或.constant(1)
,但并不知道它的好处是什么
据我所知,常量(值)返回一个函数,该函数返回给定的
值。我知道它与函数式编程有关,但为什么不直接使用const VALUE=1代码>相反?一个用例是在创建时填充数组:
Array.from({length: 5}, _.constant(1))
但如果没有它,它实际上会更短:
Array.from({length: 5}, () => 1);
发件人:
因此,主要用于将常量传递给期望函数的API。很好
只有了解功能范例,才能清楚地了解常量的用例。有了函数式编程,一切都可以用函数来表达。常量也不例外。下面是一个人为的例子:
const map=f=>xs=>
xs.map(f);
常数co=x=>y=>x;
console.log(
map(co(0))([1,2,3])/[0,0,0]
);代码>对.constant
是一个方便的函数,通常用于构造总是返回相同值的函数。我意识到匿名胖箭头函数语法的一个实例不短或可读性更好,可以是返回对象文字符号,例如.times(7,()=>{return{a:1}})
.times(7,{constant({a:1})
@jimmygoggle.times(7,()=>({a:1}))
不可变性是函数编程中的一个概念,为并发性提供了一些好处,并使函数在数学意义上变得纯粹。
// api: object.position = function(time) { return coords }
circle.position = _.constant( [10, 10] )
// api: image.fill( function(x, y) { return color })
image.fill( _.constant( black ) );