如何定义类型InfiniteFunction
,它是一个函数,调用时将返回另一个InfiniteFunction
类型如下:
() => () => () => ... // infinite
或递归:
type InfiniteFunction = () => InfiniteFunction
这不起作用
scala> type InfiniteFunction = () => InfiniteFunction
<console>:11: error: illegal cyclic reference involving type InfiniteFunction
type InfiniteFunction = () => InfiniteFunction
我想对此功能进行cps转换:
def travel(tree: TreeNode): Unit = {
if (tree != null) {
travel(tree.left)
println(tree.value)
travel(tree.right)
}
}
cps之后:
def r[T](f: => T): () => T = () => f
def travel(tree: TreeNode, cb: () => AnyRef): Unit = {
if (tree != null) {
travel(tree.left, r{
println(tree.value)
travel(tree.right, cb)
})
} else {
cb()
}
}
然后我想通过产生尾部而不是调用它们来优化尾部调用:
def r[T](f: => T): () => T = () => f
def travel(tree: TreeNode, cb: () => InfiniteFunction): InfiniteFunction = {
if (tree != null) {
r(travel(tree.left, r{
println(tree.value)
r(travel(tree.right, cb))
}))
} else {
r(cb())
}
}
// demonstration how to use travel
var f: InfiniteFunction = r(
travel(tree, r(throw new RuntimeException("it is over")))
)
// this will end by the exception "it is over"
while (true) f = f()
这里需要类型InfiniteFunction
,而没有InfiniteFunction
类型,则需要类型转换:
def r[T](f: => T): () => T = () => f
def travel(tree: TreeNode, cb: () => AnyRef): () => AnyRef = {
if (tree != null) {
r(travel(tree.left, r {
println(tree.value)
r(travel(tree.right, cb))
}))
} else {
r(cb())
}
}
var f: () => AnyRef = r(
travel(tree, r(throw new RuntimeException("it is over")))
)
while (true) f = f().asInstanceOf[() => AnyRef]
答案 0 :(得分:6)
使用特征而不是类型别名来解决循环引用的问题:
trait Inf extends (Unit => Inf)
Unit
也是()
的类型