Having
(Some(1), 2, Some(3))
I expect to get
(Some(1), Some(2), Some(3))
With shapeless is it possible to do so?
shapeless is a type class and dependent type based generic programming library for Scala.
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 .
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]]]].
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With