在下面,我试图制作一个多态函数来转换 RawFeatureValue
成RefinedFeatureValue
.
import shapeless._
object test {
type RawFeatureValue = Int :+: Double :+: String :+: CNil
type RefinedFeatureValue = Int :+: Double :+: CNil
private object convert extends Poly1 {
implicit def caseInt = at[Int](i => i)
implicit def caseDouble = at[Double](d => d)
implicit def caseString = at[String](s => s.hashCode)
}
val a = Coproduct[RawFeatureValue](12)
val b: RefinedFeatureValue = a map convert
}
但是,结果类型是
Int :+: Double :+: Int :+: CNil
与 RefinedFeatureValue
不兼容.[error] found : shapeless.:+:[Int,shapeless.:+:[Double,shapeless.:+:[Int,shapeless.CNil]]]
[error] required: test.RefinedFeatureValue
[error] (which expands to) shapeless.:+:[Int,shapeless.:+:[Double,shapeless.CNil]]
[error] val b: RefinedFeatureValue = a map convert
[error] ^
我如何告诉无形的两个
Int
s 应该被视为一个?
最佳答案
我能想到的最直接的方法是将每个元素映射到您的目标副产品,然后统一结果:
import shapeless._
type RawFeatureValue = Int :+: Double :+: String :+: CNil
type RefinedFeatureValue = Int :+: Double :+: CNil
object convert extends Poly1 {
implicit val caseInt = at[Int](Coproduct[RefinedFeatureValue](_))
implicit val caseDouble = at[Double](Coproduct[RefinedFeatureValue](_))
implicit val caseString = at[String](s =>
Coproduct[RefinedFeatureValue](s.hashCode))
}
这按预期工作:
scala> val a = Coproduct[RawFeatureValue](12)
a: RawFeatureValue = 12
scala> val b: RefinedFeatureValue = a.map(convert).unify
b: RefinedFeatureValue = 12
scala> val c = Coproduct[RawFeatureValue]("foo")
c: RawFeatureValue = foo
scala> val d: RefinedFeatureValue = c.map(convert).unify
d: RefinedFeatureValue = 101574
这个解决方案还不错,但它似乎对于单个操作来说可能足够有用。
关于scala - 无形:从副产品映射到不同的副产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29898637/