[英]Scala: How to transform an HList of ValidatedNel into a ValidatedNel of HList
[英]How to zip an HList with a plain Scala collection?
假設如何使用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 = ???
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]) :: ...
如果擔心的話。
可能,但是有限制。 通常,您必須指定要壓縮的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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.