检测无限递归? [英] Detect infinite recursion?

查看:95
本文介绍了检测无限递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有一个爬行数组的函数...

Lets assume I have a function that crawls over an array...

flatten([a, b, c, d, [e, f, g, [h, i, j, k], l], m, n, o, p])
>> [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p]

Flatten会抓取代码,并且遇到的每个数组都会递归进入该数组并返回值,使得你有一个平面数组。

Flatten would crawl over the code and for each array encountered would recursively enter into that array and return the values such that you have a flat array.

直到我们有一个如下数组:

This works until we have an array such as:

a    = [];
a[0] = a;

这显然会产生无限递归:

This obviously creates infinite recursion:

Array[1]
0: Array[1]
 0: Array[1]
  0: Array[1]
   0: Array[1]
    0: Array[1]
     0: Array[1]
      ...

如何在不修改数组的情况下检测此行为,以便函数可以处理此问题?

How can I detect this behavior without modifiying the array such that the function can deal with this?

推荐答案

如果检测递归是必需的,那么你将不得不为它交换内存空间:创建一个你解析的对象数组(递归发送的参数)并检查每个新参数。如果您已经解析了它,请立即返回。

If detecting recursion is a requirement, you're going to have to trade memory space for it: create an array of objects you parsed (the parameters you send recursively) and check each new parameter against it. If you already parsed it, return immediately.

这篇关于检测无限递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆