あり、あなたがこれを行うことができますいくつかの方法がありますが、私は、カスタム型クラスで行くと思います:
import shapeless._
trait RowSelect[L <: HList] extends DepFn2[L, Int] {
type Row <: HList
type Out = Option[Row]
}
object RowSelect {
def select[L <: HList](l: L, i: Int)(implicit rs: RowSelect[L]): rs.Out = rs(l, i)
type Aux[L <: HList, Row0 <: HList] = RowSelect[L] { type Row = Row0 }
implicit val hnilRowSelect: Aux[HNil, HNil] = new RowSelect[HNil] {
type Row = HNil
def apply(l: HNil, i: Int): Option[HNil] = Some(HNil)
}
implicit def hconsRowSelect[A, T <: HList](implicit
trs: RowSelect[T]
): Aux[List[A] :: T, A :: trs.Row] = new RowSelect[List[A] :: T] {
type Row = A :: trs.Row
def apply(l: List[A] :: T, i: Int): Option[A :: trs.Row] = for {
h <- l.head.lift(i)
t <- trs(l.tail, i)
} yield h :: t
}
}
次のように動作します。
scala> println(RowSelect.select(a, 0))
Some(1 :: a :: true :: HNil)
scala> println(RowSelect.select(a, 1))
Some(2 :: b :: false :: HNil)
scala> println(RowSelect.select(a, 2))
Some(3 :: c :: true :: HNil)
scala> println(RowSelect.select(a, 3))
None
RowSelect
インスタンスL
のためのすべてのList
要素を持つL
がhlistであり、指定されたインデックスの項目をオプションでそれぞれList
から選択する操作が提供されています。
あなたはNatTRel
またはConstMapper
とZipWith
の組み合わせとPoly2
と同じことを達成することができるはずですが、カスタム型クラスがうまく一緒にすべてをバンドルし、多くの場合、より便利compositionalityすることができます。その後、
def allRows[L <: HList](l: L)(implicit rs: RowSelect[L]): List[rs.Row] =
Stream.from(0).map(rs(l, _).toList).takeWhile(_.nonEmpty).flatten.toList
そして:
scala> allRows(a).foreach(println)
1 :: a :: true :: HNil
2 :: b :: false :: HNil
3 :: c :: true :: HNil
と同様に変換したい場合たとえば、この場合には、あなたのボーナスの質問に対する解決策はかなり素直RowSelect
の用語で記述することができ
これらのリストをタプルに変換する:
def allRows[L <: HList, R <: HList](l: L)(implicit
rs: RowSelect.Aux[L, R],
tp: ops.hlist.Tupler[R]
): List[tp.Out] =
Stream.from(0).map(rs(l, _).map(tp(_)).toList).takeWhile(_.nonEmpty).flatten.toList
u:
scala> allRows(a)
res7: List[(Int, String, Boolean)] = List((1,a,true), (2,b,false), (3,c,true))
など。
多型関数に関するいくつかの関連する質問:http://stackoverflow.com/questions/39628068/passing-an-extra-argument-into-a-polymorphic-function http://stackoverflow.com/questions/39628022/using -a-polymorphic-function-to-extract-an-object-from-options –