javascript科里化(Currying)
2009-08-30 23:51 BlueDream 阅读(1104) 评论(2) 编辑 收藏 举报首先Wiki里对Curring(科里化)的定义:
Currying is the technique of transforming a function that takes multiple arguments
in such a way that it can be called as a chain of functions each with a single argument.
意思是:将多拥有多个参数的函数形式转化为拥有单一参数的函数形式.
比如下面是一个普通求和函数:
function add(x, y) {
return x + y;
}
document.write("add(3, 4) == " + add(3, 4));
return x + y;
}
document.write("add(3, 4) == " + add(3, 4));
下面看下这个普通函数科里化的例子:
function add(x, y) {
if(x != null && y != null) return x + y; // 如果x,y都不为null.则返回x + y;
else if(x != null && y == null) {
return function(y) {
return x + y;
}
}else if(x == null && y != null){
return function(x) {
return x + y;
}
}
}
document.write("add(3, 4) == " + add(3, 4) + "<br/>");
document.write("add(3)(4) == " + add(3)(4) + "<br/>");// add(3)得到的是一个add的科里化函数
if(x != null && y != null) return x + y; // 如果x,y都不为null.则返回x + y;
else if(x != null && y == null) {
return function(y) {
return x + y;
}
}else if(x == null && y != null){
return function(x) {
return x + y;
}
}
}
document.write("add(3, 4) == " + add(3, 4) + "<br/>");
document.write("add(3)(4) == " + add(3)(4) + "<br/>");// add(3)得到的是一个add的科里化函数
最后给出一个通用的科里化转化函数:
//===========================
//
// ==== Common Curring ====
//
//===========================
function Curring(func) {
return function() {
var args = Array.prototype.slice.call(arguments, 0);
if(args.length < func.length){ // 如果形参小于实参参数
return function(){
var _args = args.concat(Array.prototype.slice.call(arguments, 0)); // 取得参数
return Curring(func).apply(this, _args); // 然后递归调用函数,获取所有参数
}
}else {
return func.apply(this, args);
}
}
}
// ==== the Common function ====
function f(x, y, z) {
alert([x, y, z])
}
var cuf = Curring(f);
cuf(2, 3, 4);
cuf(2, 3)(4);
cuf(2)(3)(4);
//
// ==== Common Curring ====
//
//===========================
function Curring(func) {
return function() {
var args = Array.prototype.slice.call(arguments, 0);
if(args.length < func.length){ // 如果形参小于实参参数
return function(){
var _args = args.concat(Array.prototype.slice.call(arguments, 0)); // 取得参数
return Curring(func).apply(this, _args); // 然后递归调用函数,获取所有参数
}
}else {
return func.apply(this, args);
}
}
}
// ==== the Common function ====
function f(x, y, z) {
alert([x, y, z])
}
var cuf = Curring(f);
cuf(2, 3, 4);
cuf(2, 3)(4);
cuf(2)(3)(4);