在 Scala 中,我们可以为低类类型定义类型级标识函数,如下所示,
type Id[A] = A
我们也可以为更高种类的类型定义类似的东西吗? IE。我们可以填空吗,
type HKId[A[...]] = ...
这样类似于 HKId[List] 的东西让我们回到 List 类型的构造函数?
绑定(bind)免费名称,例如,
type Foo[X] = List[X]
val l : Foo[Int] = List(1, 2, 3)
可能会导致我们期望更高种类的类型级别身份看起来像,
type HKId[A[X]] = A[X]
但 scalac 提示在 RHS 上找不到类型 X。
是否有一些聪明的编码可以解决问题?还是现在不可能?
最佳答案
X
在 type HKId[A[X]] = ...
是高阶类型参数。它的作用域是类型参数子句,通常在类型约束中引用。请参阅规范的§4.4:
The above scoping restrictions are generalized to the case of nested type parameter clauses, which declare higher-order type parameters. Higher-order type parameters (the type parameters of a type parameter t ) are only visible in their immediately surrounding parameter clause (possibly including clauses at a deeper nesting level) and in the bounds of t . Therefore, their names must only be pairwise different from the names of other visible parameters. Since the names of higher-order type parameters are thus often irrelevant, they may be denoted with a ‘_’, which is nowhere visible.
不久前,我们讨论了为类型函数添加文字语法的可能性,例如
[A] Either[Int, A]
.这在 Scalaz 中非常有用。同时,我们使用 Alexey 的回答中的技巧,在 PartialApplyXofY traits 中表达。 .推理会更好,但这要复杂得多,尽管 innocuous entry in Trac !)无论如何,在那个线程中,Adriaan mentioned :
It obviously won't be trivial to implement everything that logically follows from having anonymous type functions, as we currently don't have the necessary infrastructure to allow people to write higher-kinded type aliases, for example:
type MyTypeFun = [X, Y] Pair[Y, X] // desirable, but hard to support with the current implementation (we look at the type params of a symbol to infer its kind)
更新
事实证明你已经可以非常接近了:
def hk[_[_]] = ();
hk[({type A[X] = X})#A]
或者有点创意:
def hk[_[_]] = (); hk[({type \[X] = X}) # \ ]
def hk[_[_]] = (); hk[({type λ[α]=α})#λ ]
关于scala - 我们可以在 Scala 中定义一个更高种类的类型级标识函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3645631/