【发布时间】:2014-11-08 09:51:44
【问题描述】:
假设我有一个类型类来证明无形联积中的所有类型都是单例类型:
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
}
}
我们可以证明它与一个简单的 ADT 一起工作:
sealed trait Foo
case object Bar extends Foo
case object Baz extends Foo
然后:
scala> implicitly[AllSingletons[Foo, Bar.type :+: Baz.type :+: CNil]].values
res0: List[Foo] = List(Bar, Baz)
现在我们想将它与 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
}
}
我希望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]]
^
Baz.type 显然 是 单例类型。我们可以尝试手动将 Witness 实例放入作用域中,只是为了好玩:
implicit val barSingleton = Witness[Bar.type]
implicit val bazSingleton = Witness[Baz.type]
不知何故现在它起作用了:
scala> implicitly[EnumerableAdt[Foo]].values
res1: Set[Foo] = Set(Bar, Baz)
我不明白为什么这些实例可以在这种情况下工作,而由Witness.apply 宏方法(我们用来创建它们)生成的那些却不能。这里发生了什么?有没有不需要我们手动枚举构造函数的便捷解决方法?
【问题讨论】:
-
我最近修复了这方面的一些错误...用最新的快照再试一次?
-
今天推出了更多调整...第三次幸运?
-
有效!谢谢,迈尔斯!当然,我会接受你愿意做出的任何回答。
-
太棒了!感谢您的测试用例:-)
-
对于那些因为
EnumerableAdt提供的行为而最终回答这个问题的人,请查看sealerate - HT @TravisBrown
标签: scala shapeless implicits singleton-type