【发布时间】:2011-03-08 12:50:38
【问题描述】:
我为了好玩而玩弄 Scala 2.8 并试图定义一个 pimp,它为类型构造函数添加了一个“as”方法,允许从一个函子转换为另一个函子(请忽略我不一定在这里处理函子)。例如,您可以像这样使用它:
val array:Array[T]
val list:List[T] = array.as[List]
这就是我尝试做的事情:
object Test {
abstract class NatTrans[F[_], G[_]] {
def convert[T](f:F[T]):G[T]
}
implicit def array2List:NatTrans[Array, List] = new NatTrans[Array, List] {
def convert[T](a:Array[T]) = a.toList
}
// this next part gets flagged with an error
implicit def naturalTransformations[T, F[_]](f:F[T]) = new {
def as[G[_]](implicit n:NatTrans[F, G]) = n convert f
}
}
但是naturalTransformations 的定义被标记为错误“不能在参数化类型 G[T] 上存在抽象”。为了解决这个问题,我可以重写naturalTransformations 以及一个额外的类Transformable,如下所示:
class Transformable[T, F[_]](f:F[T]) {
def as[G[_]](implicit n:NatTrans[F, G]) = n convert f
}
implicit def naturalTransformations[T, F[_]](f:F[T]) = new Transformable[T, F](f)
它似乎工作。但似乎我的第一次尝试应该是等效的,所以我很好奇它为什么失败以及错误消息的含义。
【问题讨论】:
-
我习惯于在类似情况下看到错误“结构细化中的参数类型可能未引用该细化之外定义的抽象类型”。该限制与在 JVM 上通过反射 IIRC 实现结构类型的方式有关。 stackoverflow.com/questions/2685804/…
标签: scala typeclass functor implicits