使用具有不变容器的无形HLists

时间:2018-01-08 14:49:43

标签: scala shapeless

假设HList的元素是通用特征的子类。每个元素都包含在case class Box[E](elem E)中。 Box中的E 不变导致poly1映射HList,选择其父级特征等元素等问题。此处&# 39;一个例子:

import shapeless._

trait Drink[+A]{ def v: A}

case class Water(v: Int) extends Drink[Int]
case class Juice(v: BigDecimal) extends Drink[BigDecimal]
case class Squash(v: BigDecimal) extends Drink[BigDecimal]


case class Box[E](elem: E) // NB! invariance in E

object pour extends Poly1{

  implicit def caseInt[A <: Box[Drink[Int]]] =  at[A](o => Box(o.elem.v * 2))
  implicit def caseDec[A <: Box[Drink[BigDecimal]]] = at[A](o => Box(o.elem.v + 5.0))
}


object Proc {

  type I = Box[Water] :: Box[Squash] :: Box[Juice] ::  HNil
  type O = Box[Int] :: Box[BigDecimal] :: Box[BigDecimal] :: HNil

  val drinks: I = Box(Water(10)) :: Box(Squash(15.0)) :: Box(Juice(2.0)) :: HNil

  def make()(implicit m: ops.hlist.Mapper.Aux[pour.type, I, O]): O = drinks.map(pour)
}


object Main extends App{
  override def main(args: Array[String]): Unit =  Proc.make()
}

*函数pour将@Jasper_M的答案应用于Mapping over HList with subclasses of a generic trait

此代码导致 Error:(38, 22) could not find implicit value for parameter m: shapeless.ops.hlist.Mapper.Aux[pour.type,Proc.I,Proc.O] Proc.make()。 此外,过滤Proc.drinks.covariantFilter[Box[Drink[Int]]]会产生HNil。 (此过滤器将@Travis Brown的答案实现为Do a covariant filter on an HList。)

在我的项目中无法定义解决问题的Box[+E]。一个天真的解决方案 - 在pour的每个子类的Drink中都有一个案例 - 不能扩展。 (这可以通过将单态函数传递给pour来实现,我不知道如何。)

在此设置中,是否有更明智的方法来映射或过滤HLists?

1 个答案:

答案 0 :(得分:2)

在这种情况下,所有外部类型构造函数都是Box,您可以应用与我之前的答案几乎相同的技术:

object pour extends Poly1{
  implicit def caseInt[A <: Drink[Int]] =  at[Box[A]](o => Box(o.elem.v * 2))
  implicit def caseDec[A <: Drink[BigDecimal]] = at[Box[A]](o => Box(o.elem.v + 5.0))
}

现在,如果您的Box类型也是多态的,您仍然可以更进一步:

import shapeless._

trait Drink[+A]{ def v: A}

case class Water(v: Int) extends Drink[Int]
case class Juice(v: BigDecimal) extends Drink[BigDecimal]
case class Squash(v: BigDecimal) extends Drink[BigDecimal]

trait Box[E] { def elem: E}
case class ABox[E](elem: E) extends Box[E]
case class BBox[E](elem: E) extends Box[E]

object pour extends Poly1{
  implicit def caseInt[A <: Drink[Int], M[x] <: Box[x]] = at[M[A]](o => o.elem.v * 2)
  implicit def caseDec[A <: Drink[BigDecimal], M[x] <: Box[x]] = at[M[A]](o => o.elem.v + 5.0)
}


val drinks = ABox(Water(10)) :: BBox(Squash(15.0)) :: ABox(Juice(2.0)) :: HNil

drinks.map(pour)

你可能已经注意到我没有在最后一个例子中重新包装其框中的值。您仍然可以这样做,例如,如果您在trait Boxer[M[_]] { def box[A](a: A): M[A] }中实现类似Box类型类或F-bounded多态的内容,但这可能会导致我们走得太远。