【发布时间】:2018-02-02 20:36:41
【问题描述】:
我试图在折叠函数需要类型类的 HList 上运行 foldLeft。当我引入包含异常的类型类组件时,下面的说明性示例无法运行
trait MyTypeClass[T] {
def apply(t: T): String
}
object MyTypeClasses {
implicit val myInt = new MyTypeClass[Int] {
def apply(t:Int) = s"Int($t)"
}
implicit val myString = new MyTypeClass[String] {
def apply(t:String) = s"String($t)"
}
implicit val myBoolean = new MyTypeClass[Boolean] {
def apply(t:Boolean) = s"Boolean($t)"
}
}
object FoldPoly extends Poly2 {
implicit def foldToStringBuffer[U](implicit M:MyTypeClass[U]) =
at[StringBuffer, (String, U)] { (acc, t) => acc.append(t._1).append(M(t._2)) }
}
object TestRunner {
def main(args:Array[String]):Unit = {
val h = ("one" -> 1) :: ("two" -> "2") :: ("three" -> false) :: HNil
println(h.foldLeft(new StringBuffer())(FoldPoly).toString)
}
}
失败:
Error:(68, 43) could not find implicit value for parameter folder:
shapeless.ops.hlist.LeftFolder[(String, Int) :: (String, String) :: (String, Boolean) :: shapeless.HNil,StringBuffer,FoldPoly.type]
println(h.foldLeft(new StringBuffer())(FoldPoly).toString)
我发现自己不知道下一步该做什么......
【问题讨论】: