折叠HList?

时间:2016-09-01 17:17:01

标签: scala shapeless

假设:

import shapeless._
case class F(x: Option[Int], y: Option[Int])

我想帮助编写一个函数f

def f(Option[Int] :: Option[Int] :: HNil): String

这样每个Option[Int]都会替换为Some个数字或empty;和"" HNil

示例:

val res7 = Generic[F].to( F( Some(42), None) )
//res7: shapeless.::[Option[Int],shapeless.::
         [Option[Int],shapeless.HNil]] = Some(42) :: None :: HNil

f(res7) === "42empty"

如何撰写f

1 个答案:

答案 0 :(得分:2)

您需要Poly

 object OptFolder extends Poly2{
   def conv(x: Option[Int]) = x.map(_.toString).getOrElse("empty")

   implicit val ff = at{ (y: String, z: Option[Int]) => y + conv(z) }
 }

 val lala: String = myHlist.foldLeft("")(OptFolder) //:String not required

一个Generic转换为HList,然后转换为foldLeft,定义明确Poly