The issue of excessive recursion in Typescript

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

Answer №1

There is a recurring issue with this code as it results in infinite recursion since the value of n remains constant throughout, leading to repeated calls of RepeatFunction with the same unchanged value of n. To address this problem, it appears that the intent is to call the function n times; therefore, it is necessary to decrement the value of

n</code each time it is called. Alternatively, an iterative version can be implemented as shown below:</p>

<pre><code>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;
    }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Encountered an unexpected asterisk symbol while trying to import a Sequelize model from the

Currently, I am developing an application that requires me to connect and run queries on an SQL server using Sequelize. I have set up migrations, seeders, and models by utilizing sequelize init. However, when attempting to generate model objects with const ...

No testing detected, ending with code zero - NPM and YARN

After installing node js and yarn, I attempted to run an application/script developed by someone else. However, when running the test, I encountered the following message: No tests found, exiting with code 0 Watch Usage › Press f to run only failed tes ...

Is your pure function component not receiving or responding to input props correctly?

Here is my code snippet: const actionCreators = { action: AppReducer.actionCreators.action } interface GlobalState { user: Model.User | null; } interface InputState { setStashBarWidth(width: number); stashWidth: number; } const Header = ...

Which specific indexOf method is the most appropriate for my use case?

While exploring a codebase, I came across this code snippet that adds the indexOf function: if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments ...

Error: VueJS mixins do not include the property definition

I've been trying to incorporate Mixins into my Vue.js code, but I've run into a few issues :/ Here's the current code for two test modules : ErrorBaseMixin.vue <script> import ErrorAlert from './ErrorAlert'; expor ...

A new issue arises after merging in Google Datastore, as an unexpected property is

Currently, I am working on developing an API in Typescript to interact with a Google Cloud Datastore instance for storing and retrieving entities. So far, I have successfully implemented the GET, POST, and DELETE methods. However, I encountered an issue w ...

collapse each <b-collapse> when a button is clicked (initially shown)

I am facing an issue with a series of connected b-buttons and b-collapse, all initially set to be visible (open). My goal is to hide them all when a toggle from my parent.vue component is activated - so upon clicking a button in the parent component, I wa ...

JavaScript to enable button functionality for selected items

Currently, I am developing a To-Do List application. Once users input information, it gets displayed in a table format. My objective is to have the ability to select specific items from this table and apply various button functionalities to them such as ma ...

Steps for resolving the error message: "An appropriate loader is required to handle this file type, but there are no loaders currently configured to process it."

I am encountering an issue when working with next.js and trying to export a type in a file called index.ts within a third-party package. Module parse failed: Unexpected token (23:7) You may need an appropriate loader to handle this file type, current ...

Having trouble with the JQuery scrollTop animation? Getting the error message "Cannot read property 'top' of undefined"?

I am having trouble with my jquery animation scrollTop function. Whenever I click on <a>, it takes me to the anchor without any animation. Can someone please provide a solution for this issue? Upon running the webpage, I encountered an error message ...

What is the best way to receive a callback when a user cancels a dialog box to choose a mobile app after clicking on

I am currently exploring HTML coding for mobile devices and looking to integrate map routing functionality. When it comes to mobile devices, utilizing the local app is the more practical option, and I have had success implementing this by modifying the l ...

The anonymous function in the Google strategy is not being executed

I am currently working on implementing Passport to allow users to log in to my website using their Google accounts. I am utilizing yarn along with the following relevant packages: [email protected], and passport-google-oauth20@^1.0.0. The issue I am f ...

The div remains unchanged when the button is clicked

My webpage is filled with several large div elements. There's a button on the page that, when clicked, should switch to the next div. Despite my efforts, the code I've written doesn't seem to be working as expected. :( This is the HTML st ...

The Javascript regex allows for the presence of positive and negative numbers, with the option of a single minus symbol

oninput="this.value = this.value.replace(/[^-0-9.]/g, '') This code snippet is utilized in my current project. However, there seems to be an issue where the input can contain more than one minus sign, as shown here: ---23 To address this p ...

Is there a way to modify the scroll ion-content's color scheme?

Is there a way to change the scroll color in Ionic to green, specifically for ion-content? Any suggestions on how I can achieve this? Below is my HTML code: <ion-header> <ion-toolbar> <ion-buttons slot="start"> ...

Quantities with decimal points and units can be either negative or positive

I need a specialized input field that only accepts negative or positive values with decimals, followed by predefined units stored in an array. Examples of accepted values include: var inputValue = "150px"; <---- This could be anything (from the input) ...

Achieve dynamic styling and adjust window size using window.open

My mind is exhausted after days of trying: function prtDiv( o ) { var css = 'body {font:normal 10px Arial;}' ; var wo = window.open('','print','width=600,height=600,resizable=yes'); wo.document.write( '<he ...

Notification from HTML code within Django

In my Django project, I am trying to implement an alert. I am sending data from views.py to singup.html in order to display an alert based on certain conditions. However, initially the alert variable in HTML is not assigned a value. It is only after click ...

Error message in Typescript: The argument type '() => () => Socket<DefaultEventsMap, DefaultEventsMap>' cannot be assigned to a parameter of type 'EffectCallback'

I am struggling to comprehend how I should specifically type constrain in order to prevent the error within my useEffect. One approach is to either cast my newSocket or specify the return value of my useEffect as any, but I am hesitant about that solution. ...

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...