St. St. - 10 days ago 8
Scala Question

Sort HList by pattern

Suppose I have an hlist

val hlist: Boolean :: Int :: HNil = true :: 42 :: HNil


and I have a pattern

type Pattern = Int :: Boolean :: HNil


How can I reorder existing hlist with the pattern? I.e.

reorder[Int :: Boolean :: HNil](hlist) // 42 :: true :: HNil

Answer

You're looking for align and the corresponding Align type class in shapeless.ops.hlist,

scala> import shapeless._
import shapeless._

scala> val hlist: Boolean :: Int :: HNil = true :: 42 :: HNil
hlist: shapeless.::[Boolean,shapeless.::[Int,shapeless.HNil]] = true :: 42 :: HNil

scala> type Pattern = Int :: Boolean :: HNil
defined type alias Pattern

scala> hlist.align[Pattern]
res0: Pattern = 42 :: true :: HNil
Comments