Kevin Meredith Kevin Meredith - 3 months ago 22
Scala Question

Folding over HList?

Given:

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


I'd like help to write a function,
f
:

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


such that each
Option[Int]
is replace with the
Some
number or
empty
; and
""
for
HNil
.

Example:

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"


How can
f
be written?

Answer

You need a 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

So a Generic to transform to the HList and then a foldLeft with a well defined Poly.