如何用一个Scala流压缩HList来生成成对的HList?具体来说:
import shapeless._
val a = 1.3 :: true :: "z" :: HNil
val b = Stream.from(1)
val ab: (Double, Int) :: (Boolean, Int) :: (String, Int) :: HNil = ???
答案 0 :(得分:1)
trait Zipper[A <: HList, B] {
type Out <: HList
def zip(a: A, bs: Stream[B]): Out
}
implicit def hnilZipper[B] = new Zipper[HNil, B] {
type Out = HNil
def zip(a: HNil, bs: Stream[B]): HNil = HNil
}
implicit def consZipper[Head, Tail <: HList, B](implicit z: Zipper[Tail, B]) = new Zipper[Head :: Tail, B] {
type Out = (Head, B) :: z.Out
def zip(a: Head :: Tail, bs: Stream[B]): Out = {
(a.head, bs.head) :: z.zip(a.tail, bs.tail)
}
}
def zip[A <: HList, B](a: A, b: Stream[B])(implicit z: Zipper[A, B]): z.Out = z.zip(a, b)
正如Marth所说,存在安全问题,如果Stream短于HList,则这将失败。但是如果您担心的话,您可以很容易地修改它以返回Option[(A1, B) :: (A2, B) :: ...]
或(A1, Option[B]) :: (A2, Option[B]) :: ...
。
答案 1 :(得分:1)
有可能,但是有限制。通常,您必须指定要压缩的Scala集合的所需长度。结果当然是两个HList中较短者的长度。
import shapeless._
import syntax.std.traversable._ // toHList
val a = 1.3 :: true :: "z" :: HNil // 3 elements
val short_b = Stream.from(1).take(2).toHList[Int::Int::HNil]
val long_b = Stream.from(7).take(5).toHList[Int::Int::Int::Int::Int::HNil]
toHList
返回一个Option[HList]
,因此我们将对结果进行map
以提取HList
进行压缩。
short_b.map(a zip _) // 2 element result
//res0: Option[(Double, Int) :: (Boolean, Int) :: HNil] =
// Some((1.3,1) :: (true,2) :: HNil)
long_b.map(a zip _) // 3 element result
//res1: Option[(Double, Int) :: (Boolean, Int) :: (String, Int) :: HNil] =
// Some((1.3,7) :: (true,8) :: (z,9) :: HNil)