對比scala,用javascript實現curried方法

scala從語法上提供了curried方法,如:javascript

def add(x: Int, y: Int, z: Int) = x + y + z
val addCurried = (add _).curried
add(1, 2, 3) // => 6
addCurried(1)(2)(3) // => 6

val add2 = (x: Int, y: Int, z: Int) => x + y + z
val addCurried2 = add.curried
add(1, 2, 3) // => 6
addCurried(1)(2)(3) // => 6

scala 在函數式和麪向對象以及二者的結合上都比javascript走的更遠,並且語法上至關的精簡。
可是js也太靈活了,不少特性都和模擬出來。java

用javascript 對 curried 方法的實現:
代碼連接:https://github.com/peichao01/test2/tree/master/javascript/curriedgit

Function.prototype.curried = function(argsLength){
     var self = this, len = argsLength === undefined ? self.length : argsLength;
     if(len > 0){
          function curried (time, stack){
               return function(x){
                    stack[time] = x;
                    if(stack.length < len) {
                         return curried(time + 1, stack.concat());
                    } else {
                         return self.apply(self, stack);
                    }
               }
          }
          return curried(0, []);
     }
     else{
          return function(){
               return self.apply(self);
          }
     }
};

var adder = function(x, y, z){ // 在 javascript 中使用函數定義,和將匿名函數賦值給變量基本上沒有什麼區別
    return x + y + z
}
var t = function(){}
var p = function (a) {
     return a + 1
}

// var a = adder.curried();
// var a1 = a(1)(2)(3);

var aa = adder.curried();
var aa1 = aa(1);
var aa2 = aa1(2);
var aa3 = aa2(3);
console.log(aa3);
console.log(aa1(-10)(23));

var ab2 = aa1(5);
var ab3 = ab2(6);
console.log(ab3);

console.log(aa(3)(5)(10));
console.log(aa(25)(50)(12));
console.log(aa1(-10)(23));

var t1 = t.curried();

var p1 = p.curried();
var p2 = p1(2);
相關文章
相關標籤/搜索