Curryed function takes one more argument than expected | بلاگ

Curryed function takes one more argument than expected

تعرفه تبلیغات در سایت

آخرین مطالب

امکانات وب

Vote count: 0

I tried to make my own function "Curryer" in javascript ES2015 (ES6).

It seems like there is something wrong with my implementation, since i always have to give one more argument than i expect. Do note, however, that this extra argument does not get passed to the curryed function, it can also be left as undefined and nothing bad happens. The whole thing is a mess of closures so i am having a hard time debugging it even though it is really few lines of code.

By the way, i know i am reinventing the wheel here, you don't need to tell me. I am making this for learning purposes. That's why i would prefer an explanation of why this doesn't work, instead of just a fixed version of my code.

function curry(f){

  let mid = (args, newArg, argc) => {

    // if there are more arguments to process:
    // pass an array with all processed arguments to the next recursive call
    // and construct a function that takes a new argument
    if(argc > 1){
      let nextArgs = [...args];
      nextArgs.push(newArg);
      return x => mid(nextArgs, x, argc-1);
    }

    // i am guessing that a special case for argc==2 is needed

    // once all arguments have been gathered recursively, call the function
    return f(...args);
  }

  // take a pair of arguments and pass them along
  // this adds the requirement for a special case when f(...) takes a single argument.
  // but you really dont need to curry f(...) if that is the case...
  return x => y => mid([x],y,f.length);
}

Use example:

let f = (a,b,c,d)=>a+b+c+d;
let cf = curry(f);

console.log(cf(1)(2)(3)(4)()) // 10

TL;DR: I wish to get rid of that last set of parenthesis.

asked 51 secs ago
Sebastián Mestre

...
نویسنده : استخدام کار بازدید : 16 تاريخ : سه شنبه 15 اسفند 1396 ساعت: 5:59