我试图了解如何通过部分应用函数来删除参数
I'm trying to understand how to remove arguments with partialy applying a function
为什么 words2 和 words 给出相同的结果?我知道一些柯里化,但我无法理解下面的这个例子。
function curry(fn) {
const arity = fn.length;
return function $curry(...args) {
if (args.length < arity) {
return $curry.bind(null, ...args);
}
return fn.call(null, ...args);
};
}
const split = curry((sep, str) => str.split(sep));
const words = split(' ');
const words2 = str => split(' ', str)
console.log(words('something cool'))
console.log(words2('something cool'))
words 等于 split(' ') 函数,但是当我用字符串再次调用 words 时会发生什么,它怎么会等于 words2 函数?
因为split(' ', str)
和split(' ')(str)
给出了相同的结果
而调用words2
调用前者而调用words
调用后者
当您将 curry
应用于 split
函数时,就像取回拆分函数的两个版本:
function split(sep, str){
str.split(sep);
}
和
function split(sep) {
return function(str) {
return str.split(sep);
}
}
调用哪一个取决于提供的参数个数。因此,对于 words
的情况,您使用 ' '
调用第二个版本,然后使用 'something cool'
调用返回的函数,这意味着实际代码 运行 是:
'something cool'.split(' ')
在 words2
的另一种情况下,您调用第一个版本和实际代码 运行:
'something cool'.split(' ')
这就是你得到相同结果的原因。
为什么 words2 和 words 给出相同的结果?我知道一些柯里化,但我无法理解下面的这个例子。
function curry(fn) {
const arity = fn.length;
return function $curry(...args) {
if (args.length < arity) {
return $curry.bind(null, ...args);
}
return fn.call(null, ...args);
};
}
const split = curry((sep, str) => str.split(sep));
const words = split(' ');
const words2 = str => split(' ', str)
console.log(words('something cool'))
console.log(words2('something cool'))
words 等于 split(' ') 函数,但是当我用字符串再次调用 words 时会发生什么,它怎么会等于 words2 函数?
因为split(' ', str)
和split(' ')(str)
给出了相同的结果
而调用words2
调用前者而调用words
调用后者
当您将 curry
应用于 split
函数时,就像取回拆分函数的两个版本:
function split(sep, str){
str.split(sep);
}
和
function split(sep) {
return function(str) {
return str.split(sep);
}
}
调用哪一个取决于提供的参数个数。因此,对于 words
的情况,您使用 ' '
调用第二个版本,然后使用 'something cool'
调用返回的函数,这意味着实际代码 运行 是:
'something cool'.split(' ')
在 words2
的另一种情况下,您调用第一个版本和实际代码 运行:
'something cool'.split(' ')
这就是你得到相同结果的原因。