scala - 无形:从副产品映射到不同的副产品

标签 scala unions shapeless

在下面,我试图制作一个多态函数来转换 RawFeatureValueRefinedFeatureValue .

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 :+: CNilRefinedFeatureValue 不兼容.
[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/

相关文章:

无处不在的无形和异步计算

java SimpleDateFormat解析毫秒格式错误

javascript - 在 AngularJS $scope 中访问 Play Scala 变量

Scala 修饰符和类型参数化

c++ - 如何初始化指向 nullptr 的指针 union ?

c++ - 了解 union 的内存内容

c++ - 匿名 union 和普通 union

Scala:没有getter就不能写setter?

scala - 如何将两个元组与兼容的类型结合起来?

scala - Shapeless 中 TypeClass 特征的 emptyCoproduct 和 coproduct 方法的目的是什么