javascriptfunctionfunctional-programmingcurryingchurch-encoding

How to make a function call itself n times


Let's say I have a function called f that takes an integer argument called x and returns an integer. I also have an integer n that says how many times the function must call itself. So for example if my function call looks like this f(x) when n = 1, then it would look like this f(f(f(x))) when n = 3. How could something like that look in my example bellow:

function succ(n) {
  return function (f, x) {
    return f(x);
  };
}

Solution

  • You could loop inside the inner function:

     for(let i = 0; i < n; i++) x = f(x);
     return x;
    

    or alternatively let your function call itself:

     return n > 0 ? succ(n - 1)(f, f(x)) : x;