这是“Scala 中的函数式编程”第 13 章中的一个练习,用于实现一个用于解释尾递归函数的蹦床。
runTrampoline2
不是尾递归的,并且会用我的测试输入溢出堆栈。此外,该tailrec
注释给出了一个编译器错误runTrampoline2
。 runTrampoline
是尾递归的并通过注解的编译时检查。
我最好的选择是这两个蹦床之间的区别在于val
捕获或不捕获单位的方式,如下所示:
scala> val foo = println("abc")
val foo = println("abc")
abc
foo: Unit = ()
scala> foo
foo
scala> val bar: Int = {println("xyz"); 5}
val bar: Int = {println("xyz"); 5}
xyz
bar: Int = 5
scala> bar
bar
res8: Int = 5
否则这两个蹦床看起来和我一模一样。如果有人评论它们对这个问题很重要,我将包含 Free monad 和 Suspend、Return 和 FlatMap 构造函数的代码,但我认为它们不是。的尾递归是否被从 srunTrampoline2
中泄漏出来的副作用破坏了val
?谢谢!
@annotation.tailrec
def runTrampoline[A](tra: Free[Function0,A]): A =
tra match {
// case Return(A)
case Return(a1) => a1
// case Suspend(Function0[A])
case Suspend(function0A1) => function0A1()
// case FlatMap(Free[Function0[_],A], A=>Free[Function0,B]]
case FlatMap(free1, aFree2) => free1 match {
// case Return(A)
case Return(a2) => runTrampoline(aFree2(a2))
// case Suspend(Function0[A])
case Suspend(function0A) => runTrampoline(aFree2(function0A()))
// case FlatMap(Free[Function0[_],A], A=>Free[Function0,B]]
case FlatMap(a0,g) =>
runTrampoline {
a0 flatMap { a0 => g(a0) flatMap aFree2 }
}
}
}
//@annotation.tailrec
def runTrampoline2[A](tra: Free[Function0,A]): A =
tra match {
// case Return(A)
case Return(a1) => a1
// case Suspend(Function0[A])
case Suspend(function0A1) => {
val a1: A = function0A1()
a1
}
// case FlatMap(Free[Function0[_],A], A=>Free[Function0,A]]
case FlatMap(free1, aFree2) => free1 match {
// case Return(A)
case Return(a2) => {
val free2: Free[Function0,A] = aFree2(a2)
val a3: A = runTrampoline2(free2)
a3
}
// case Suspend(Function0[A])
case Suspend(function0A) => {
val a2: A = function0A()
val free2: Free[Function0,A] = aFree2(a2)
val a3: A = runTrampoline2(free2)
a3
}
// case FlatMap(Free[Function0[_],A], A=>Free[Function0,B]]
case FlatMap(a0,g) =>
runTrampoline2 {
a0 flatMap { a0 => g(a0) flatMap aFree2 }
}
}
}
一个月前我问了一个类似的问题,关于打破尾递归的类型注释: Scala: type annotations make tail recursion check fail
由艾文解决。这是蹦床的修正版本。每个递归调用都位于包含它的案例的最后。
@annotation.tailrec
def runTrampoline3[A](tra: Free[Function0,A]): A =
tra match {
case Return(a1) => a1
case Suspend(function0A1) => {
val a1 = function0A1()
a1
}
case FlatMap(free1, aFree2) => free1 match {
case Return(a2) => {
val free2 = aFree2(a2)
runTrampoline3(free2)
}
case Suspend(function0A) => {
val a2 = function0A()
val free2 = aFree2(a2)
runTrampoline3(free2)
}
case FlatMap(a0,g) =>
runTrampoline3 {
a0 flatMap { a0 => g(a0) flatMap aFree2 }
}
}
}