递归函数是高阶函数的特例

时间:2014-11-05 15:17:07

标签: recursion computer-science higher-order-functions

维基百科声明:

  

在数学和计算机科学中,高阶函数(也是   功能形式,功能或功能)是一个功能   至少下列之一:

     
      
  • 将一个或多个功能作为输入
  •   
  • 输出功能
  •   

此外,

  

递归函数是一个在其中调用自身的函数   执行。

这是否意味着递归函数可以归类为高阶函数的一个非常特殊的情况?

请参考此案例:

int foo(int i)
{
    if(i>10)
    {
       return 10;
    }
    cout<<i;
    return foo(++i);
}

我不想要意见。请在具体前提下说明您的答案。

3 个答案:

答案 0 :(得分:2)

没有

输出一个函数意味着函数可以用作函数的返回值,就像这样(Lua中的代码):

function foo()
    return function(a,b) return a + b end
end

在递归函数的示例中,返回值是表达式foo(++i)的结果,而不是函数foo本身的结果。

答案 1 :(得分:2)

想象一下你的Algol方言不支持递归但支持高阶函数。我们还能实施你的例子吗?当然可以!

int foo_aux(int i, Func cont)
{
    if( i>10 ) {
       return 10;
    } else {
       cout<<i;                 // side effect bad!
       return cont(i+1, cont);  // no recursion
    }
}

int foo(int i)
{
    return foo_aux(i, [] (int i, Func cont) -> int { return foo_aux(i,cont) });
}

想象一下,您尝试做同样的事情,但您的语言不支持高阶函数或递归。是否有可能效仿它?一切皆有可能:

std::stack<int> args;       // integers can be castable pointers or numbers!
int cont = 2;
while( cont ) {
  if( cont == 2 ) {         // main
      args.push(1)
      cont=1;               // continuation == foo_aux
  } else if ( cont == 1 ) { // foo_aux
      int tmp = args.pop();
      if( tmp > 10 ) {
          args.push(10);
          cont=0;           // continuation == return/exit
      } else {
          cout << tmp;
          args.push(tmp+1);
          // not setting cont == recursion
      }
  }
}
// do something with the result
return args.pop();

这是一种在初始示例中进行递归的方法。也许你可以制作一个预处理器(宏)来从像你的例子这样的东西进行转换,以便编译。如果您想将该函数作为参数传递,只需按下该数字,您的接收函数就需要设置f

std::stack<int> args;       // integers can be castable pointers or numbers!
args.push(2)                // bootstrap
int cont = 0;
while( cont = args.pop() ) {
  if( cont == 2 ) {            // main / foo
      args.push(1)             // push argument
      args.push(1)             // push function
  } else if ( cont == 1 ) {    // foo_aux
      int tmp = args.pop();
      if( tmp > 10 ) {
          args.push(10);       // push result
          args.push(0);        // push exit as continuation 
      } else {
          cout << tmp;
          args.push(tmp+1);    // push argument
          args.push(1);        // push self as argument
      }
  }
}
// do something with the result
return args.pop();

这不支持所谓的向上funarg,因为那时你需要有另一个结构来封闭变量不再在范围内。

递归是高阶函数的一个特例吗?由于可以使用函数索引模拟函数,因此可以从编译器视点同时实现函数,递归和高阶函数。这仅意味着可以以相同的方式建模功能。完全有可能使编译器使用不支持更高阶函数但支持递归的汇编函数,并且可以创建一个没有递归的语言来支持更高阶函数,这将使得能够以类似{{3}的方式进行递归。 }}。除此之外,它们完全不同。

答案 2 :(得分:0)

没有。在此上下文中“输出”函数意味着返回一个函数,而不是返回调用函数的结果。也就是说,返回值本身是可调用的。递归函数通常不一定这样做。例如:

def factorial(n: int) -> int:
    if n == 0:
        return 1
    else:
        return n*factorial(n-1)

此代码返回一个整数。您不能调用整数,因此它不是高阶函数。

相关问题