我在递归函数上看过的每本教科书都使用了阶乘 例如,这很有帮助,但并不完全有启发性。
出于编程目的,递归函数可以将函数作为其基础 case,它可以在其体内包含其他函数调用,还是可以执行 不同的递归水平有何不同?
如果它执行这些任何这些事情,它仍然是一个'递归功能' 或者现在是别的什么?
答案 0 :(得分:3)
递归函数的定义只是“调用自身的函数”。因此,如果你有一个自己调用的函数,它就是一个递归函数。
其他任何事情都取决于您正在使用的语言的功能。
答案 1 :(得分:2)
这是递归函数的一个相当简单的例子,它简单地将集合中的所有值(表示为堆栈的数组)输出到浏览器控制台,因为它使用.pop()方法将它们弹出堆栈
totalSize值在整个调用堆栈中不会改变,因此可以通过将当前堆栈大小除以原始大小来测量中间点。
要回答这个问题,它在递归的不同层次上的表现会有所不同,答案是肯定的:
// a simple array of 10 items
var coll = [1,2,3,4,5,6,7,8,9,10];
// recursive function that calls itself. It behaves slightly different at
// the halfway point
function test(totalSize, col) {
if(col == undefined || col.length == 0) {
return 0;
} else {
if(col.length / totalSize < .5) {
console.log("Past 1/2 way point!");
}
console.log("total = " + totalSize);
console.log("col.pop() = " + col.pop());
return test(totalSize, col);
}
}
// make a call to the function with the total size and the collection
test(coll.length, coll);
此外,您还询问是否可以调用其他功能,这也是可能的。在下面的示例中,函数用于返回基本案例的结果, 并且函数用于抽象中途点行为:
// a simple array of 10 items
var coll = [1,2,3,4,5,6,7,8,9,10];
// recursive function that calls itself. It behaves slightly different at
// the halfway point
function test(totalSize, col) {
if(col == undefined || col.length == 0) {
return handleBaseCase(totalSize, col);
} else {
// handle if it's at 1/2 way point
handleHalfwayPoint(totalSize, col);
console.log("tital = " + totalSize);
console.log("col.pop() = " + col.pop());
return test(totalSize, col);
}
}
function handleHalfwayPoint(totalSize, collection) {
if(collection.length / totalSize < .5) {
console.log("Past 1/2 way point!");
}
}
// instead of returning 0, return "Done" and also print to the log
function handleBaseCase(totalSize, collection) {
console.info("Done!");
return "Done!";
}
// make a call to the function with the total size and the collection
test(coll.length, coll);
虽然这些特定示例无法解决任何实际问题,但它演示了如何在另一个函数内调用函数的概念可以扩展以处理其他用例。教科书中的示例旨在教您递归的基础知识,并帮助您掌握将来处理更复杂的现实问题所需的工具。
由于这种函数式语言是JavaScript,因此运行它们的障碍很小。您可以通过在Chrome开发者控制台中运行代码来尝试这些示例,也可以在小型测试HTML文件中运行它们。祝你好运!
答案 2 :(得分:1)
递归函数是一种在其体内调用自身一次或多次的函数。函数也可以是相互递归的,其中一个函数是根据第二个函数定义的,反之亦然。
我已经编程超过20年而不需要递归。是什么让我真正理解递归调用的需要和美感是Scheme语言,以及诸如“The Little Schemer”之类的书籍。
并非所有编程语言都支持同级别的递归。 Scheme是那些做得很好的人之一。 Python更不用说了。因此,如果您想深入了解递归,请检查您的编程语言的能力。
答案 3 :(得分:1)
正如其他答案所说,递归函数是一个自我调用的函数。解释有两种类型here:
我在你的问题中看到了数学标记。递归与数学归纳有关。如果你证明它可以解决基本情况然后你证明如果无限序列语句中的任何一个语句都是真的,那么下一个语句也是如此,你证明它将在任何情况下解决问题。