Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shapeless: map a tuple with some options to options

Having

(Some(1), 2, Some(3))

I expect to get

(Some(1), Some(2), Some(3))

With shapeless is it possible to do so?

like image 285
DANG Fan Avatar asked Jul 28 '15 08:07

DANG Fan


People also ask

What is Scala Shapeless?

shapeless is a type class and dependent type based generic programming library for Scala.

What is an HList?

A HList is a List where the type of every element is statically known at compile time. You may see them as "tuples on steroid". The beauty of HList compared to tuples is that you'll find all the essential List methods like take , head , tail , map , flatMap , zip , etc. plus a bunch of methods specific to HList .

What is HList in Scala?

HList is a recursive data structure. In Scala, we can write any pair type like ::[H, T] in a more ergonomic way like H :: T, so the type of our hlist is either Int :: Double :: String :: Boolean :: HNill or ::[Int, ::[Double, ::[String, ::[Boolean, HNill]]]].


1 Answers

Yes it is,

scala> import shapeless._, syntax.std.tuple._
import shapeless._
import syntax.std.tuple._

scala> :paste
// Entering paste mode (ctrl-D to finish)

object opt extends opt0 {
  implicit def optId[T <: Option[_]] = at[T](identity)
}
trait opt0 extends Poly1 {
  implicit def default[T] = at[T](Option(_))
}

// Exiting paste mode, now interpreting.

defined object opt
defined trait opt0

scala> (Some(1), 2, Some(3)) map opt
res0: (Some[Int], Option[Int], Some[Int]) = (Some(1),Some(2),Some(3))

You'll notice that the Some[Int]'s at the first and last position have been preserved whereas the lifted middle element is typed as Option[Int]. I've worked on the assumption that what you actually intended was something like this,

scala> (Option(1), 2, Option(3)) map opt
res1: (Option[Int], Option[Int], Option[Int]) = (Some(1),Some(2),Some(3))
like image 148
Miles Sabin Avatar answered Nov 09 '22 11:11

Miles Sabin