在 Scala 中,如何使类型类适用于 Aux 模式? [英] In scala, how to make type class working for Aux pattern?
问题描述
这是一个简单的例子:
trait Base {
type Out
def v: Out
}
object Base {
type Aux[T] = Base { type Out = T }
class ForH() extends Base {
type Out = HNil
override def v: Out = HNil
}
object ForH extends ForH
}
class TypeClass[B]
trait TypeClassLevel1 {
def summon[B](b: B)(implicit ev: TypeClass[B]): TypeClass[B] = ev
}
object TypeClass extends TypeClassLevel1 {
implicit def t1: TypeClass[Base.Aux[HNil]] = new TypeClass[Base.Aux[HNil]]
implicit def t2: TypeClass[Int] = new TypeClass[Int]
}
it("No Aux") {
val v = 2
TypeClass.summon(v) // works
}
it("Aux") {
val v = new Base.ForH()
TypeClass.summon(v) // oops
TypeClass.summon(Base.ForH) // oops
val v2 = new Base.ForH(): Base.Aux[HNil]
TypeClass.summon(v2) // works!
}
对象 Base/ForH 显然有一个稳定的路径,这消除了编译器无法解析类型 ForH.Out
的可能性.
The object Base/ForH clearly has a stable path, this eliminate the possibility of the compiler not being able to resolve type ForH.Out
.
让我烦恼的不是编译器是如何无法弄清楚 ForH <:<Aux[HNil]
,但是修补它是多么容易,只需一个简单的类型向上转换(最后两行).恕我直言,这两个特性(类型 lambda 和类型类)都是函数式编程的重要方面,为什么它们不能同时工作?
What bothers me is not how incapable the compiler is to figure out the fact that ForH <:< Aux[HNil]
, but how easy it is to patch it up, just by a simple type upcast (last 2 lines). IMHO both features (type lambda & type classes) are important aspect of functional programming, why they can't work together at the same time?
如果您熟悉编译器设计,我将有一个额外的问题:如何改进类型类搜索算法以实现它?非常感谢您的意见.
If you are familiar with the compiler design I'll have an extra question: what does it take to improve the type class search algorithm to make it happen? Thanks a lot for your opinion.
更新 1:已经提出了一个特定的修复程序,但我在尝试概括它时遇到了另一个问题,请参阅 在 scala 中,如何使类型类适用于 Aux 模式?- 第 2 部分详情
UPDATE 1: a specific fix has been proposed but I have another problem trying to generalise it, please see In scala, how to make type class working for Aux pattern? - Part 2 for detail
推荐答案
所以编译器能够推断 ForH <:<Aux[HNil]
,但是(tbh 我不知道确切的原因)当返回类型使用类型 lambda 时解析隐式时,如果您不使用类型绑定,它会感到困惑.
So the compiler is able to infer ForH <:< Aux[HNil]
, but (tbh I don't know exactly why) when resolving an implicit when the return type uses a type lambda, it gets confused if you don't use a type bound.
无论如何这可能不是一个很好的解释,但至少我可以让你的代码编译.只需将 t1
更改为:
Anyway that's probably not a great explanation, but at least I can make your code compile. Just change t1
to:
implicit def t1[T <: Base.Aux[HNil] ]: TypeClass[T] = new TypeClass[T]
这对我在 scastie 中使用 Scala 2.13.4 有效.
this works for me in scastie using Scala 2.13.4.
这篇关于在 Scala 中,如何使类型类适用于 Aux 模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!