代码之家  ›  专栏  ›  技术社区  ›  Svein Bringsli

在Delphi中:如何在不使用参数的情况下找到递归深度?

  •  2
  • Svein Bringsli  · 技术社区  · 14 年前

    procedure Recurse(<Params>; aDepth : integer = 0);
    begin
      if aDepth > SomeLimit then
      begin
        //Tidy up, return best result found>
        exit;
      end;
    
      <stuff>
    
      if <Condition> then
        Recurse(<Params>; aDepth+1)
      else 
      begin 
        //Tidy up, return result of endnode>
      end;
    end;
    

    我称之为没有深度参数

    Recurse(<Params>);
    

    有没有其他方法可以轻松找到深度?

    5 回复  |  直到 14 年前
        1
  •  7
  •   Chris Thornton    14 年前

    在我看来,简单的解决方案在这里是最好的,它是可移植的,而且是经得起未来考验的,不像你能发明的任何堆栈窥探解决方案。
    是的,还有其他的方法,但是你最初的解决方案是最好的。

        2
  •  2
  •   Eduardo Mauro    14 年前

    在过程中声明类型化常量。确保将compile选项设置为允许更改常量。

    procedure Recurse;
    const
      aDepth : integer = 0;
    begin
      aDepth := aDepth + 1;
    
      try
        if aDepth > SomeLimit then
        begin
          //Tidy up, return best result found>
          exit;
        end;
    
        <stuff>
    
        if <Condition> then
          Recurse
        else 
        begin 
          //Tidy up, return result of endnode>
        end;
      finally
        aDepth := aDepth - 1;
      end;
    end;
    
        3
  •  0
  •   Eugene Mayevski 'Callback    14 年前

    有一个可以计算递归的全局变量吗?否则,no-recursion只是用一些参数调用某个方法。

        4
  •  0
  •   Alsk    14 年前

    在C++中,我能做到这一点。

    class recursion_guard
    {
    public:
        recursion_guard() { depth_count++; }
        ~recursion_guard() { depth_count--; }
        static int depth_count;
    };
    int recursion_guard::depth_count = 0;
    void recurse(recursion_guard a = recursion_guard())
    {
        if(recursion_guard::depth_count > 100)
            return;
        recurse();
    }
    

    const 
        MyRecursionGuardConstString: string = "whatever";
    procedure Recurse(RecursionGuard: string = MyRecursionGuardConstString) 
    begin
        if GetRefCount(MyRecursionGuardConstString) > 100 then //o_o
            exit;
        end;
        Recurse;
    end;
    
        5
  •  0
  •   Shreq    14 年前
    type
      TMyRecursion = class
      private
        nDepth: integer;
      public
        constructor Create;
        procedure Recursion(...)
      end;
    

    当然,在构造函数中必须初始化nDepth。