这是编写 curry 函数的正确递归方式吗?

Is this the correct recursive way to write curry function?

我无法理解这个递归 curry 函数是否正确。

function curry(fn) {
  return function curryInner(...args) {
    if (args.length >= fn.length) return fn(...args);
    return function (...next) {
      return curryInner(...args, ...next);
    };
  };
}

const example = {
  multiplier: 5,
  calculate: function (a, b) {
    return (a + b) * this.multiplier;
  },
};
example.curriedVersion = curry(example.calculate);

console.log(example.calculate(1, 2));
console.log(example.curriedVersion(1)(2));

我有带绑定的 curry 函数实现,但我不确定为什么它有效而递归无效。你能帮我理解一下吗,我认为我对这个函数的上下文理解不正确

function curry(func) {
    return function curried(...args) {

        if (args.length >= func.length) {
            return func.apply(this, args)
        } else {
            return curried.bind(this, ...args)
        }
    }
}

你的curring是正确的,问题出在this.multiplier

当您使用表达式 example.calculate 而不调用函数时,它不会绑定 this。所以 this.multiplier 将是 undefined.

使用 example.calculate.bind(example),您的柯里化将按预期工作。

function curry(fn) {
  return function curryInner(...args) {
    if (args.length >= fn.length) return fn(...args);
    return function (...next) {
      return curryInner(...args, ...next);
    };
  };
}

const example = {
  multiplier: 5,
  calculate: function (a, b) {
    return (a + b) * this.multiplier;
  },
};
example.curriedVersion = curry(example.calculate.bind(example));

console.log(example.calculate(1, 2));
console.log(example.curriedVersion(1)(2));