1

I am trying to learn Typescript in combination with some exercises. I can't figure out why I am getting this error of too much recursion. I made some wrapper-functions.

Wrapper-functions

type Fun<a,b> = {
   f: (i:a) => b
   then: <c>(g:Fun<b,c>) => Fun<a,c>
}

let myFunction = function<a,b>(f:(_:a) => b) : Fun<a,b> {
    return {
       f:f,
       then: function<c>(this:Fun<a,b>, g:Fun<b,c>) : Fun<a,c> {
           return then(this,g);
       }
    }
};

let then = function<a,b,c>(f: Fun<a,b>, g:Fun<b,c>) : Fun<a,c> {
    return myFunction(a => g.f(f.f(a)))
};

I'd like to create my own RepeatFunction so to say, whereas I can pass a function and an amount of executes as parameters.

My code

let increase = myFunction<number,number>(x => x + 1);

let RepeatFunction = function<a>(f: Fun<a,a>, n: number) : Fun<a,a> {
   if (n < 0)
   {
       return myFunction(x => f.f(x));
   }
   else
   {
       for (let i = 0; i < n; i++)
       {
           RepeatFunction(myFunction<a,a>(x => this.f(x)), n); //error in console
       }
   }
};

console.log(RepeatFunction(increase, 2).f(10));

I'd like to call RepeatFunction, pass in my increase-function with to execute 2 times on number 10.

I am getting the error: 'Too much recursion'. Could anyone tell me what I am missing here? There are no syntax errors.

edit 2

let RepeatFunction = function<a>(f: Fun<a,a>, n: number) : Fun<a,a> {
   if (n < 0)
   {
       return myFunction(x => f.f(x));
   }
   else
   {
       return RepeatFunction(myFunction<a,a>(x => f.f(x)), n - 1);
   }
};

console.log(RepeatFunction(incr, 1).f(10));  // answer is: 11
console.log(RepeatFunction(incr, 5).f(10));  // answer is: 11
console.log(RepeatFunction(incr, 50).f(10)); // answer is: 11
J. Doe
  • 35
  • 4
  • repeat = RepeatFunction, thank you for noticing. Edited my post – J. Doe Feb 27 '18 at 13:04
  • Possible duplicate of [How to implement a stack-safe chainRec operator for the continuation monad?](https://stackoverflow.com/questions/48967530/how-to-implement-a-stack-safe-chainrec-operator-for-the-continuation-monad) – Thomas Feb 27 '18 at 13:06

1 Answers1

2

The problem is that this is infinitely recursive because n never changes in value, you always call RepeatFunction with the same n. My guess is you want to call it n times, so you should decrease n next time you call it, or you can use an iterative version :

let RepeatFunction = function<a>(f: Fun<a,a>, n: number) : Fun<a,a> {
    if (n < 1)
    {
        return myFunction(x => f.f(x));
    }
    else
    {
        var fn = myFunction<a,a>((x) => f.f(x));
        for (var i = 0; i < n; i++) {
            fn = fn.then(f);
        }
        return fn;
    }
};
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357