我有以下内容:
sealed trait baseData {
def weight: Int
def priority: Int
}
sealed trait moreData {
def weight: Int
def priority: Int
def t: String
def id: String
}
case class data1(override val weight: Int, override val priority: Int) extends baseData
case class moreData1 (override val weight:Int, override val priority: Int, override val t: String, override val id: String)extends moreData
我正在从案例类中生成HLists:
val h1 = LabelledGeneric[data1].to(data1(1,2))
val h2 = LabelledGeneric[moreData1].to(moreData1(3,4,"a","b"))
如何修剪或过滤h2
,使其仅包含h1
中的字段?我觉得我需要类似val filtered = h2.foldRight(HNil)(keepFunc)
的东西,但却无法弄清楚如何写keepFunc
。有任何想法吗?
答案 0 :(得分:0)
您可以根据键进行过滤。代码不是通用的,但希望足以说明这个概念。
val gen1 = LabelledGeneric[data1]
val gen2 = LabelledGeneric[moreData1]
val h1 = gen1.to(data1(1,2))
val h2 = gen2.to(moreData1(3,4,"a","b"))
val keys1 = Keys[gen1.Repr].apply
val keys2 = Keys[gen2.Repr].apply
object pair extends Poly2 {
implicit def default[T, U] = at[T, U]((_, _))
}
object keep extends Poly2 {
implicit def keepFunc[T, K, L <: HList] =
at[(T, K), L] { case ((t, key), l) =>
if (keys1.toList.contains(key)) t :: l else l
}
}
val filtered = h2.zipWith(keys2)(pair).foldRight(HNil)(keep)