【问题标题】:'Too much recursion'-error in Typescript“递归过多”-Typescript 中的错误
【发布时间】:2018-02-27 13:01:22
【问题描述】:

我正在尝试结合一些练习来学习 Typescript。我不知道为什么我会得到这个递归过多的错误。我做了一些包装函数。

包装函数

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)))
};

可以这么说,我想创建自己的 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));

我想调用RepeatFunction,传入我的增加函数以在数字10上执行2次。

我收到错误:“递归过多”。谁能告诉我我在这里缺少什么?没有语法错误。

编辑 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

【问题讨论】:

标签: javascript typescript console.log


【解决方案1】:

问题在于这是无限递归的,因为n 的值永远不会改变,你总是用相同的n 调用RepeatFunction。我的猜测是你想调用它n 次,所以你应该在下次调用它时减少n,或者你可以使用迭代版本:

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

【讨论】:

  • 感谢您的回答。我在控制台中的结果是:'TypeError: RepeatFunction(...) is undefined'
  • @J.Doe 代码中还有其他问题,现在修复它们
  • (见编辑 2) Ty,它现在运行,但我没有得到预期的输出。我是否在函数调用中更改 n 并不重要,我总是得到 11 作为结果。但它应该在数字 10 上增加 n 次。
  • @J.Doe 是的,我也看到了,我猜你想f(f(f.. n times... f(0))为此添加了一个非递归版本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-14
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
  • 1970-01-01
相关资源
最近更新 更多