Currently, I am in the process of learning Typescript while working on some exercises. While attempting to solve a particular problem, I encountered an error related to excessive recursion. This issue arises even though I created wrapper functions.
About 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)))
};
My aim is to create a customized RepeatFunction where I can specify a function and the number of times it should run as parameters.
Implementation of RepeatFunction
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));
The objective is to invoke RepeatFunction with the 'increase' function and execute it twice on the number 10.
However, I'm encountering a 'Too much recursion' error. Any insights into what might be causing this? No syntax errors have been identified thus far.
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