Splitting an HList that was concatenated using Prepend[A, B]

随声附和 提交于 2019-12-05 03:57:23

You can do this fairly straightforwardly with Split:

import shapeless._, ops.hlist.{ Length, Prepend, Split }

class UndoPrependHelper[A <: HList, B <: HList, C <: HList, N <: Nat] {
  def apply(c: C)(implicit split: Split.Aux[C, N, A, B]): (A, B) = split(c)
}

def undoPrepend[A <: HList, B <: HList](implicit
  prepend: Prepend[A, B],
  length: Length[A]
) = new UndoPrependHelper[A, B, prepend.Out, length.Out]

And then:

scala> type A = Int :: String :: Symbol :: HNil
defined type alias A

scala> type B = List[Int] :: Option[Double] :: HNil
defined type alias B

scala> type C = Int :: String :: Symbol :: List[Int] :: Option[Double] :: HNil
defined type alias C

scala> val a: A = 1 :: "foo" :: 'bar :: HNil
a: A = 1 :: foo :: 'bar :: HNil

scala> val b: B = List(1, 2, 3) :: Option(0.0) :: HNil
b: B = List(1, 2, 3) :: Some(0.0) :: HNil

scala> val c: C = a ++ b
c: C = 1 :: foo :: 'bar :: List(1, 2, 3) :: Some(0.0) :: HNil

scala> val (newA: A, newB: B) = undoPrepend[A, B].apply(c)
newA: A = 1 :: foo :: 'bar :: HNil
newB: B = List(1, 2, 3) :: Some(0.0) :: HNil

I recently added an "undo" operation for the Remove type class, and it might make sense to have something similar built into Prepend.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!