【发布时间】:2014-01-01 01:58:35
【问题描述】:
我有这个 scala 函数,由于性能问题,需要重写为尾递归。在处理不太大的数据集时堆栈会爆炸,因此我得出结论,只有通过使其尾递归才能修复它。 这是函数::
private def carve2(x: Int, y: Int) {
var rand: Int = random.nextInt(4)
(1 to 4) foreach { _ =>
val (x1, y1, x2, y2) = randomize(x, y, rand)
if (canUpdate(x1, y1, x2, y2)) {
maze(y1)(x1) = 0
maze(y2)(x2) = 0
carve2(x2, y2)
}
rand = (rand + 1) % 4
}
}
主要问题是::
> How to get rid of the foreach/for loop
为此,我尝试了一种递归方法,但要获得正确的语义很棘手,特别是因为在 if 块内自调用之后,rand var 的值发生了变化...
我尝试的是将rand的状态修改推出身体,并在作为参数传递时对其进行变异::
def carve3(x: Int, y: Int, rand: Int) {
for (i <- 1 to 4) {
val (x1, y1, x2, y2) = randomize(x, y, rand)
if (canUpdate(x1, y1, x2, y2)) {
maze(y1)(x1) = 0
maze(y2)(x2) = 0
if (i == 1) carve3(x2, y2, random.nextInt(4))
else carve3(x2, y2, (rand + 1) % 4)
}
}
}
这不起作用...
还有一件事,我知道这种编码方法不起作用,但我正在努力实现……这是我尝试重构的代码。 此外,randomize 和 canUpdate 函数与此上下文无关。
有什么建议吗? 提前非常感谢...
【问题讨论】:
标签: scala recursion functional-programming tail-recursion