在开始学习lisp时,我遇到了尾递归这个术语.这究竟是什么意思?
language-agnostic algorithm recursion functional-programming tail-recursion
如果我们在算法中使用循环而不是递归,反之亦然,那么两者是否可以起到同样的作用?例如:检查给定的字符串是否为回文.我已经看到许多程序员使用递归作为一种手段来展示一个简单的迭代算法可以适应账单.编译器在决定使用什么方面起着至关重要的作用吗?
我面临一个问题,即递归和使用循环似乎都是自然的解决方案.对于像这样的案件,是否有惯例或"首选方法"?(显然它不像下面那么简单)
Item Search(string desired, Scope scope) {
foreach(Item item in scope.items)
if(item.name == desired)
return item;
return scope.Parent ? Search(desired, scope.Parent) : null;
}
Run Code Online (Sandbox Code Playgroud)
Item Search(string desired, Scope scope) {
for(Scope cur = scope; cur != null; cur = cur.Parent)
foreach(Item item in cur.items)
if(item.name == desired)
return item;
return null;
}
Run Code Online (Sandbox Code Playgroud) 我有这个方法来计算一些统计数据:
public void calculateAverage(int hour){
if (hour != 20) {
int data =0;
int times = 0;
for (CallQueue cq : queues) {
data += cq.getCallsByTime().get(hour);
times++;
}
averageData.add((double)data/times);
calculateAverage(hour + 1);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我非常自豪我创建了一个递归方法,但我知道这可以通过循环解决.
我的问题是:递归或循环解决这些问题会更好吗?
如果你有时间解释你的答案,请