【发布时间】:2011-03-16 02:06:59
【问题描述】:
我有这个方法
private def getAddresses(data: List[Int], count: Int, len: Int): Tuple2[List[Address], List[Int]] = {
if (count == len) {
(List.empty, List.empty)
} else {
val byteAddress = data.takeWhile(_ != 0)
val newData = data.dropWhile(_ != 0).tail
val newCount = count + 1
val newPosition = byteAddress.length + 1
val destFlag = byteAddress.head
if (destFlag == SMEAddressFlag) {
(SMEAddress().fromBytes(byteAddress) :: getAddresses(newData, newCount, len)._1, newPosition :: getAddresses(newData, newCount, len)._2)
} else {
(DistributionList().fromBytes(byteAddress) :: getAddresses(newData, newCount, len)._1, newPosition :: getAddresses(newData, newCount, len)._2)
}
}
}
我很想重写它
private def getAddresses(data: List[Int], count: Int, len: Int): Tuple2[List[Address], List[Int]] = {
if (count == len) {
(List.empty, List.empty)
} else {
val byteAddress = data.takeWhile(_ != 0)
val newData = data.dropWhile(_ != 0).tail
val newCount = count + 1
val newPosition = byteAddress.length + 1
val destFlag = byteAddress.head
val nextIter = getAddresses(newData, newCount, len)
if (destFlag == SMEAddressFlag) {
(SMEAddress().fromBytes(byteAddress) :: nextIter._1, newPosition :: nextIter._2)
} else {
(DistributionList().fromBytes(byteAddress) :: nextIter._1, newPosition :: nextIter._2)
}
}
}
我的问题是
- 第一个尾递归吗?
- 它是如何工作的?我在最后一行调用了该方法两次。它会评估分离的方法调用吗?
- 哪个版本更高效,或者我怎样才能更高效地编写它。
如果代码有异味请原谅我是 scala 的新手。
谢谢
【问题讨论】:
-
在你的函数中添加
@tailrecannotation 会让编译器告诉你它是否不是尾递归的。
标签: scala recursion tail-recursion