偏函数和函数柯里化

偏函数 (Partial application)

In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity.

在计算机科学中,局部应用是指固定一个函数的一些参数,然后产生另一个更小元的函数。(什么是元?元是指函数参数的个数,比如一个带有两个参数的函数被称为二元函数。)

没有上下文的偏函数
1
2
3
4
5
6
7
const partial = (fn, ...args) => {
return (...args2) => fn.call(this, ...args, ...args2)
}

console.log(partial(function (a, b, c, d) {
return a + b + c + d
}, 1, 2)(3, 4))
bind 实现
  • 类型判断,错误处理
  • 缓存一级参数
  • 定义返回的新函数
  • 处理原型链
  • 绑定新函数的执行上下文,判断是否通过new调用
1
2
3
4
5
6
7
8
9
10
11
12
13
Function.prototype.bind = function (ctx) {
if (typeof this !== 'function') throw new Error();
var args = Array.prototype.slice.call(arguments, 1);
var toBind = this;
var fn = function _fn() {
args = args.concat(Array.prototype.slice.call(arguments, 0))
toBind.apply(this instanceof _fn ? this : ctx, args)
}
if (toBind.prototype) {
fn.prototype = Object.create(toBind.prototype)
}
return fn;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Function.prototype.bind = function (ctx) {
if (typeof this !== 'function') throw new Error();
var args = Array.prototype.slice.call(arguments, 1);
var toBind = this;
var noop = function(){}
var fn = function _fn() {
args = args.concat(Array.prototype.slice.call(arguments, 0))
toBind.apply(noop.prototype.isPrototypeOf(this) ? this : ctx, args)
}
if (toBind.prototype) {
noop.prototype = toBind.prototype;
}
fn.prototype = new noop()
return fn;
}

柯里化 (Currying)

In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument.

在数学和计算机科学中,柯里化是一种将使用多个参数的一个函数转换成一系列使用一个参数的函数的技术

ES6实现
1
2
const curry = (fn, args = []) =>
fn.length === args.length ? fn(...args) : (...args2) => curry(fn, [...args, ...args2])
反柯理化

使用箭头函数不能绑定函数的this

1
const uncurry = (fn) => (...args) => fn.apply(this, args)
1
2
3
4
5
6
Function.prototype.uncurring = function () {
var self = this;
return function () {
return self.apply(this, arguments);
};
};

偏函数与柯里化区别

柯里化是将一个多参数函数转换成多个单参数函数,也就是将一个 n 元函数转换成 n 个一元函数。

局部应用则是固定一个函数的一个或者多个参数,也就是将一个 n 元函数转换成一个 n - x 元函数。

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2025 SunZhiqi

此时无声胜有声!

支付宝
微信