将HList转换为HLists的HList

时间:2014-07-02 17:06:21

标签: scala shapeless

如何将HList转换为HLists的HList,如下面的代码段所示。

import shapeless._
import Nat._

case class A(i: Int)
case class B(str: String)
case class C(i: Int, str: String)

type Input = A :: B :: C :: HNil
val in: Input = A(1) :: B("b") :: C(2, "c") :: HNil

type X = A :: HNil
val x: X = A(1) :: HNil

type Y = A :: B :: HNil // could also be B :: HNil
val y: Y = A(1) :: B("b") :: HNil

type Z = A :: C :: HNil // could also be B :: C :: HNil
val z: Z = A(1) :: C(2, "c") :: HNil

type Output = X :: Y :: Z :: HNil
val out: Output = x :: y :: z :: HNil

// Illustrates what I want to accomplish.
def build(in: Input) : Output = {
  val x: X = in(_0) :: HNil
  val y: Y = in(_0) :: in(_1) :: HNil
  val z: Z = in(_0) :: in(_2) :: HNil
  x :: y :: z :: HNil
}

println(build(in) == out) // true


def magic[In <: HList, Out <: HList](in: In) : Out = ???
println(magic[Input, Output](in) == out)

我希望通过Output方法构建Input给定magic,该方法以某种方式映射输入并最终得到build个输出。

1 个答案:

答案 0 :(得分:4)

对于自定义类型类,这不是太糟糕。请注意,从某种意义上说,我们需要两个基本情况&#34; -one启动顶层HList,一个启动每个内部HList。然后,归纳步骤显示如何将新项目(我们知道如何从输入中提取)添加到我们添加的最后一个HList

import shapeless._, ops.hlist.Selector

trait Picker[I <: HList, O <: HList] {
  def apply(i: I): O
}

object Picker {
  implicit def hnilPicker[I <: HList]: Picker[I, HNil] = new Picker[I, HNil] {
    def apply(i: I) = HNil
  }

  implicit def hnilHlistPicker[I <: HList, OT <: HList](implicit
    picker: Picker[I, OT]
  ): Picker[I, HNil :: OT] = new Picker[I, HNil :: OT] {
    def apply(i: I) = HNil :: picker(i)
  }

  implicit def hlistPicker[I <: HList, OHH, OHT <: HList, OT <: HList](implicit
    sel: Selector[I, OHH],
    picker: Picker[I, OHT :: OT]
  ): Picker[I, (OHH :: OHT) :: OT] = new Picker[I, (OHH :: OHT) :: OT] {
    def apply(i: I) = picker(i) match {
      case h :: t => (sel(i) :: h) :: t
    }
  }
}

然后:

def magic[In <: HList, Out <: HList](in: In)(implicit
  picker: Picker[In, Out]
): Out = picker(in)

最后:

scala> println(magic[Input, Output](in))
A(1) :: HNil :: A(1) :: B(b) :: HNil :: A(1) :: C(2,c) :: HNil :: HNil

scala> println(magic[Input, Output](in) == out)
true

能够仅指定输出类型并推断输入类型是很好的,但遗憾的是没有方便的方法来实现它。