0

在运行时我可以:

def X(R: Any): Any = X(R)

但不能为编译时做类似的事情:

scala> type X[R] = X[R]
<console>:11: error: illegal cyclic reference involving type X
       type X[R] = X[R]
                   ^

似乎是无限循环/递归保护,但据我了解停止问题- 没有通用方法来检测图灵完备语言的无限递归(因为检测器本身可能不会停止),因此额外的编译器检查通常不会在这里工作.

那么有没有办法在scalac上获得无限递归?而且,还有其他(除了防止这种递归)理由illegal cyclic reference吗?

4

1 回答 1

0

使用递归结合多态性,有一种棘手的方法可以在 scalac 上获取 StackOverflow:

scala> trait Re { type X[R <: Re] }
warning: there were 1 feature warning(s); re-run with -feature for details
defined trait Re

scala> trait ReRe extends Re {type X[R <: Re] = R#X[R]}
defined trait ReRe

scala> type X = ReRe#X[ReRe]
java.lang.StackOverflowError

它之所以起作用,是因为编译器认为它R#X[R]是调用的Re,但实际上ReRe是在计算时传递type X的。

不知道目的illegal cyclic reference- 也许它只保护编译器内部的无限循环,而不是无限递归(如果使用非尾递归实现图灵完整性)。

于 2015-02-04T06:21:32.587 回答