简体   繁体   中英

Shapeless HList foldLeft with type class requirement in operation

Im trying to run a foldLeft on an HList where the folding function requires a typeclass. The below illustrative example fails to run the moment I introduce the typeclass component with the included exception

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)

  }
}

With the Failure:

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)

I find my self at a loss for what to try next...

Your typeclass instances are not in the implicit scope. Rename object to MyTypeClass so it is considered a companion or import its contents:

object TestRunner {
  def main(args:Array[String]):Unit = {
    import MyTypeClasses._
    val h = ("one" -> 1) :: ("two" -> "2") :: ("three" -> false) :: HNil
    println(h.foldLeft(new StringBuffer())(FoldPoly).toString)

  }
}

Works in scastie

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM