Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

科里化 #7

Open
kangkang123269 opened this issue Mar 2, 2023 · 0 comments
Open

科里化 #7

kangkang123269 opened this issue Mar 2, 2023 · 0 comments
Labels
JavaScript JavaScript基础

Comments

@kangkang123269
Copy link
Owner

kangkang123269 commented Mar 2, 2023

科里化是将一个函数拆分成多个函数的过程,每个函数都是接收一个参数并返回一个新函数,直到最后一个函数返回最终的结果。科里化可以将函数的参数分解成多个较小的部分,这样更方便使用函数,也更容易重用函数。

下面是几个科里化的变形题:

  1. 反科里化(uncurrying)
    反科里化是将一个已经科里化的函数恢复成一个接收多个参数的函数。可以使用Function.prototype.bind方法来实现反科里化。
function add(a) {
  return function(b) {
    return a + b;
  };
}

const uncurriedAdd = Function.prototype.bind.call(add, null);
console.log(uncurriedAdd(1, 2)); // Output: 3
  1. 偏函数(partial application)

偏函数是指在一个已经科里化的函数基础上,固定部分参数,返回一个新的函数。可以使用Function.prototype.bind方法或者箭头函数来实现偏函数。

function add(a, b) {
  return a + b;
}

const partialAdd = Function.prototype.bind.call(add, null, 1);
console.log(partialAdd(2)); // Output: 3

const arrowPartialAdd = (b) => add(1, b);
console.log(arrowPartialAdd(2)); // Output: 3
  1. 组合函数(compose)

组合函数是指将多个函数组合成一个函数,新函数将参数传递给最后一个函数,并将返回值传递给倒数第二个函数,以此类推,直到第一个函数返回结果。可以使用reduce方法来实现组合函数。

function add1(x) {
  return x + 1;
}

function multiply2(x) {
  return x * 2;
}

function square(x) {
  return x * x;
}

const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);

const composedFn = compose(square, multiply2, add1);
console.log(composedFn(3)); // Output: 64

以上是几个常见的科里化的变形题,它们可以扩展科里化的应用场景,并且可以提高代码的可读性和重用性。

@kangkang123269 kangkang123269 added the JavaScript JavaScript基础 label Sep 7, 2023
@kangkang123269 kangkang123269 changed the title js5. 科里化 科里化 Sep 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JavaScript基础
Projects
None yet
Development

No branches or pull requests

1 participant