我是新來的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