Scala:关于 shapeless 将 HList 转换为 List 的问题

Scala: Question about shapeless to tranform HList to List

我是 shapeless 的新手(并且在 scala 的学习曲线中仍然处于低水平......)并且我在 shapeless 方面遇到了一些困难

import shapeless._
case class FooBar[T](foo: String, bar: T)
val hl = 0 :: FooBar("A", "one") :: FooBar("B", 1) :: "0" :: FooBar("C", "two") :: HNil
val l = hl.filter[FooBar[String]].toList
println(l) //List(FooBar(A,one), FooBar(C,two))

工作正常

下一步,我想把它放在函数中,比如

def filter[T](hl: HList): List[FooBar[T]] = ???

所以我可以简化对

的调用
filter[String](hl)
filter[Int](hl)

我天真地测试了

def filter[T](hl: HList): List[FooBar[T]] = {
  hl.filter[FooBar[T]].toList
}

给出

 could not find implicit value for parameter partition: shapeless.ops.hlist.Partition[shapeless.HList,FooBar[T]]

在尝试使用隐式后,我仍然没有找到正确的方法

你有什么想法吗?

谢谢!

如果您缺少一些隐式函数,那么在您的方法中您应该假设它们已被提供。说该方法的参数类型只是 HList(而不是某些特定的 L <: HList)太粗略了。

因为你可能想指定 T 而不是指定 L (期望 L 将被推断)尝试类型 class + 扩展方法

import shapeless._
import shapeless.ops.hlist.{Partition, ToTraversable}

case class FooBar[T](foo: String, bar: T)
val hl = 0 :: FooBar("A", "one") :: FooBar("B", 1) :: "0" :: FooBar("C", "two") :: HNil

trait FilterFooBar[L <: HList, T] {
  def apply(l: L): List[FooBar[T]]
}

object FilterFooBar {
  implicit def mkFilterFooBar[L <: HList, T, Prefix <: HList, Suffix <: HList](implicit
    partition: Partition.Aux[L, FooBar[T], Prefix, Suffix],
    toTraversable: ToTraversable.Aux[Prefix, List, FooBar[T]]
  ): FilterFooBar[L, T] = _.filter.toList    
}

implicit class FilterFooBarOp[L <: HList](l: L) {
  def filterFooBar[T](implicit filterFooBarInstance: FilterFooBar[L, T]): List[FooBar[T]] = 
    filterFooBarInstance(l)
}

println(hl.filterFooBar[String]) // List(FooBar(A,one), FooBar(C,two))
println(hl.filterFooBar[Int]) // List(FooBar(B,1))