【问题标题】:Folding over HList?折叠 HList?
【发布时间】:2016-09-02 01:44:48
【问题描述】:

给定:

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怎么写?

【问题讨论】:

    标签: scala shapeless


    【解决方案1】:

    你需要一个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

    【讨论】:

    • 谢谢,@wheaties。 conv是什么意思,即函数名?
    猜你喜欢
    • 2018-10-29
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 2016-10-26
    相关资源
    最近更新 更多