import shapeless._
import syntax.singleton._
val book = ("author" ->> "Benjamin Pierce") ::
("title" ->> "Types and Programming Languages") ::
("id" ->> "foo") ::
("price" ->> "bar") ::
HNil
我想找到映射到"foo"
的字段键(在本例中为"id"
)并检索它,键入为4个单例字符串的Coproduct。
我该怎么做?
答案 0 :(得分:2)
我建议使用自定义类型做一些不同的(更通用的):
import shapeless._
import shapeless.labelled.FieldType
trait RecSearch[R <: HList, A] {
type Keys <: Coproduct
def find(r: R, a: A): Option[Keys]
}
object RecSearch extends LowPriorityRecSearchInstances {
implicit def hnilRecSearch[A]: Aux[HNil, A, CNil] =
new RecSearch[HNil, A] {
type Keys = CNil
def find(r: HNil, v: A): Option[CNil] = None
}
implicit def cconsRecSearch1[K, V, T <: HList](implicit
trs: RecSearch[T, V],
wit: Witness.Aux[K]
): Aux[FieldType[K, V] :: T, V, K :+: trs.Keys] =
new RecSearch[FieldType[K, V] :: T, V] {
type Keys = K :+: trs.Keys
def find(r: FieldType[K, V] :: T, a: V): Option[K :+: trs.Keys] =
if (r.head == a)
Some(Coproduct[K :+: trs.Keys](wit.value))
else trs.find(r.tail, a).map(_.extendLeft[K])
}
}
trait LowPriorityRecSearchInstances {
type Aux[R <: HList, A, K <: Coproduct] = RecSearch[R, A] { type Keys = K }
implicit def cconsRecSearch0[A, K, V, T <: HList](implicit
trs: RecSearch[T, A]
): Aux[FieldType[K, V] :: T, A, K :+: trs.Keys] =
new RecSearch[FieldType[K, V] :: T, A] {
type Keys = K :+: trs.Keys
def find(r: FieldType[K, V] :: T, a: A): Option[K :+: trs.Keys] =
trs.find(r.tail, a).map(_.extendLeft[K])
}
}
然后:
def search[R <: HList, A](r: R)(a: A)(implicit rs: RecSearch[R, A]): Option[rs.Keys] =
rs.find(r, a)
最后:
import syntax.singleton._
val book = ("author" ->> "Benjamin Pierce") ::
("title" ->> "Types and Programming Languages") ::
("id" ->> "foo") ::
("price" ->> "bar") ::
HNil
search(book)("foo")
这将显示(非常详细)的副产品类型和正确的值:
Some(Inr(Inr(Inl(id))))
您的版本不能为我编译,所以我无法真正比较这两个,但95%的时间我开始使用Poly
我最终会在某个时候切换到类型类。
答案 1 :(得分:0)
我需要折叠HList,构建一个Coproduct(或Option[Coproduct]
)。
object folder extends Poly2 {
implicit def apply[K : Witness.Aux, C <: Coproduct] = at[FieldType[K, Float], Option[C]] { (value, result) =>
result.fold(
if (value == "foo") Some(Coproduct[K :+: C](implicitly[Witness.Aux[K]].value)) else None
)(result => Some(result.extendLeft[K]))
}
}
book.foldRight(Option.empty[CNil])(folder) // Option