我是新来的Scala编程人员。 我的目标是实施一个河内塔问题的尾递归程序。 我相信它可以通过递归这样实现:Scala中河内塔的尾递归
// Implementing a recursive function for Towers of Hanoi,where the no of disks is taken as 'n', 'from' being the Start Peg, 'to' being the End Peg, and 'via' being Intermediate Peg
def move(n: Int, from: Int, to: Int, via: Int) : Unit = { // Recursive Function
if (n == 1) {
Console.println("Move disk from pole " + from + " to pole " + to)// each move iteration printed.
}
else {
move(n - 1, from, via, to) //Moving n-1 disks from source to Intermediate
move(1, from, to, via) // Printing all the move iterations
move(n - 1, via, to, from) //Moving n and other n-1 disks to the final destination
}
}
它能否实现并采用尾递归呢?
我不认为有一个简单的方法使尾部递归。尾递归本质上与迭代循环相同。 – SpiderPig