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

Unlocking the potential: Clicking on all ng-if elements with matching text using Chrome console

I am currently trying to determine how to automatically click on all elements that have a specific state. The page appears to be built using Angular, although I am unsure of the exact version being used. My approach involves using the console in Chrome t ...

Stripping out only the position attribute using jQuery

I have implemented a code with the following characteristics: The navigation items' texts are hidden behind certain Divs, which I refer to as Navigation Divs. When the mouse hovers over these pixels (navigation Divs), the text that is behind the ...

When you click on `window.open('my-app://', '_blank');`, it won't directly open the desktop app from the browser. However, typing `my-app://`

When I open Chrome and enter my-app:// in the URL or search bar, a dialog box pops up saying "Open my-app? A website wants to open this application". Clicking ok opens my Electron app. I'm looking to add similar functionality to my React app, where t ...

What exactly are AngularJS module dependencies and how do they work together?

After exploring the tutorial example provided on AngularJs's site ( here) (The main HTML appears to be quite minimal with only ng-view and ng-app=phonecatApp included) Within the app.js file, we find: var phonecatApp = angular.module('phoneca ...

The issue of onClick failing to function when paired with the addEventListener for the

Looking into a react component for a profile button that opens a menu with three options: My Profile, Settings, and Logout. The issue seems to be with the onClick event on the a tags not working as expected (the console.log is not being printed). Interes ...

What is the best way to generate multiple progress bars by leveraging a for loop?

Exploring the code snippet below, I've been creating a progress bar that reacts to specific data input in array form. However, the issue I've encountered is that the code only generates a single progress bar. How can I incorporate this into my f ...

Instructions on uploading a PDF file from a Wordpress page and ensuring the file is stored in the wp-content upload directory folder

What is the process for uploading a PDF file on a WordPress page? <form action="" method="POST"> <input type="file" name="file-upload" id="file-upload" /> <?php $attachment_id = media_handle_upload('file-upload', $post->I ...

Using innerHTML in React to remove child nodes Tutorial

I'm encountering slow performance when unmounting over 30,000 components on a page using conditional rendering triggered by a button click. This process takes around 10+ seconds and causes the page to hang. Interestingly, setting the parent container& ...

What methods can I use to integrate Cheerio with CSS Manipulation?

I've been working on a web scraping project using axios, cheerio, and express. However, every time I attempt to run the project, it encounters errors. For testing purposes, I am using a test page from my friend's website. Here is the code snippe ...

Strange Reselect selector actions

It seems like my selector function is only triggered when one of the arguments changes, not both. Here's the selector I'm using to retrieve transactions from the state and apply two filters to them: export const getFilteredTransactionsSelector ...

Tips for resolving issues related to Nodemailer configuration

I am currently working on a script that sends form data to an email address. I am using Express and Nodemailer with Node.js, but as a beginner, I am struggling to understand why the email authorization stops and prevents the letters from being sent. Here ...

The dilemma of selecting objects in Three.js

Currently, I am developing a small web application that utilizes three.js. However, I have encountered an issue: I created a prototype with my three.js content and everything functions correctly (the canvas size in the prototype matches the browser window ...

JavaScript checkboxes not being recognized by Node element

Located on the left side of the page, there is a feature that allows me to include selected options in a list with the same name attribute. These selections will then be sent as part of the entire form to the Node backend. Most of the elements on the page ...

Leverage the power of ssh2-promise in NodeJS to run Linux commands on a remote server

When attempting to run the command yum install <package_name> on a remote Linux server using the ssh2-promise package, I encountered an issue where I couldn't retrieve the response from the command for further processing and validation. I' ...

When a page is changed, the Vue.js Active Menu color remains enabled

Check out my website at . I want to customize the navigation bar so that only the active page's navbar li is colored in red. <div class="navigation-items"> <ul class="nav-list"> <li class="nav-item"><nuxt-link to="/en" ...

What is the behavior of the JavaScript event loop when a Promise's resolution is tied to setTimeout?

console.log('1') setTimeout(() => { console.log('2') }, 0) function three() { return new Promise(resolve => { setTimeout(() => { return new Promise(resolve => resolve('3')) },0) ...

Verify whether a variable is empty or not, within the sequence flows in Camunda Modeler

When working with a sequenceFlow in a process instance, I need to check a condition that may involve a variable that has not been defined yet. I want the flow to proceed even if the variable is not defined, rather than throwing an ActivitiException. I hav ...

Identify and handle errors effectively using TypeScript

I have a question regarding my Express server setup. Here is the code snippet: import express from "express"; import helmet from "helmet"; import cors from "cors"; const app = express(); app.use(helmet()); app.use(cors()); a ...

The "Splash Screen Div" page displayed during transitions and page loading

Creating a "Splash Screen Div" for a loading page involves waiting until everything is loaded and then hiding or moving the div off screen. Below is an example: index.html <div id="loading-Div"> <div id="bear-Logo"> < ...

Switch the website title as soon as the user looks away from the tab

How can I capture the user's attention and bring them back to my website when they are on a different tab? I really like the effect used on sephora.pl where an alert pops up with the message 'What are you waiting for?' when you switch tabs. ...