Tra*_*own 52 scala implicits shapeless singleton-type
假设我有一个类型类,证明Shapeless副产品中的所有类型都是单例类型:
import shapeless._
trait AllSingletons[A, C <: Coproduct] {
def values: List[A]
}
object AllSingletons {
implicit def cnilSingletons[A]: AllSingletons[A, CNil] =
new AllSingletons[A, CNil] {
def values = Nil
}
implicit def coproductSingletons[A, H <: A, T <: Coproduct](implicit
tsc: AllSingletons[A, T],
witness: Witness.Aux[H]
): AllSingletons[A, H :+: T] =
new AllSingletons[A, H :+: T] {
def values = witness.value :: tsc.values
}
}
Run Code Online (Sandbox Code Playgroud)
我们可以证明它适用于简单的ADT:
sealed trait Foo
case object Bar extends Foo
case object Baz extends Foo
Run Code Online (Sandbox Code Playgroud)
然后:
scala> implicitly[AllSingletons[Foo, Bar.type :+: Baz.type :+: CNil]].values
res0: List[Foo] = List(Bar, Baz)
Run Code Online (Sandbox Code Playgroud)
现在我们想要将它与Shapeless的Generic机制结合起来,它将为我们提供ADT的联合产品表示:
trait EnumerableAdt[A] {
def values: Set[A]
}
object EnumerableAdt {
implicit def fromAllSingletons[A, C <: Coproduct](implicit
gen: Generic.Aux[A, C],
singletons: AllSingletons[A, C]
): EnumerableAdt[A] =
new EnumerableAdt[A] {
def values = singletons.values.toSet
}
}
Run Code Online (Sandbox Code Playgroud)
我希望implicitly[EnumerableAdt[Foo]]能够工作,但事实并非如此.我们可以-Xlog-implicits用来获取有关原因的一些信息:
<console>:17: shapeless.this.Witness.apply is not a valid implicit value for
shapeless.Witness.Aux[Baz.type] because:
Type argument Baz.type is not a singleton type
implicitly[EnumerableAdt[Foo]]
^
<console>:17: this.AllSingletons.coproductSingletons is not a valid implicit
value for AllSingletons[Foo,shapeless.:+:[Baz.type,shapeless.CNil]] because:
hasMatchingSymbol reported error: could not find implicit value for parameter
witness: shapeless.Witness.Aux[Baz.type]
implicitly[EnumerableAdt[Foo]]
^
<console>:17: this.AllSingletons.coproductSingletons is not a valid implicit
value for AllSingletons[Foo,this.Repr] because:
hasMatchingSymbol reported error: could not find implicit value for parameter
tsc: AllSingletons[Foo,shapeless.:+:[Baz.type,shapeless.CNil]]
implicitly[EnumerableAdt[Foo]]
^
<console>:17: this.EnumerableAdt.fromAllSingletons is not a valid implicit
value for EnumerableAdt[Foo] because:
hasMatchingSymbol reported error: could not find implicit value for parameter
singletons: AllSingletons[Foo,C]
implicitly[EnumerableAdt[Foo]]
^
<console>:17: error: could not find implicit value for parameter e:
EnumerableAdt[Foo]
implicitly[EnumerableAdt[Foo]]
^
Run Code Online (Sandbox Code Playgroud)
Baz.type但显然是单身人士.我们可以尝试Witness手动将实例放在范围内以获得乐趣:
implicit val barSingleton = Witness[Bar.type]
implicit val bazSingleton = Witness[Baz.type]
Run Code Online (Sandbox Code Playgroud)
不知怎的,它现在有效:
scala> implicitly[EnumerableAdt[Foo]].values
res1: Set[Foo] = Set(Bar, Baz)
Run Code Online (Sandbox Code Playgroud)
我不明白为什么这些实例在这种情况下会起作用,而Witness.apply宏方法(我们用来创建它们)生成的实例则不然.这里发生了什么?是否有一个方便的解决方法,不需要我们手动枚举构造函数?
| 归档时间: |
|
| 查看次数: |
3357 次 |
| 最近记录: |