In shapeless, have two lists, so one contains classes of the other

In formless, I try to write a function such that it takes two HLists l1 and l2 arbitrary length, which have the following properties:

  • The lengths l1 and l2 are the same
  • l2 contains the exact types of l1 wrapped in a constructor with a constant external type.

So if l1 was

 1 :: 1.2 :: "hello" :: HNil` 

l2 maybe

 Ordering[Int] :: Ordering[Double] :: Ordering[String] :: HNil 

Using UnaryTCConstraint and LengthAux , I can limit the lengths and require a static external constructor for l2 , however the problem of their correspondence has become a problem.

Any ideas on how I can do this?

+8
scala shapeless
source share
1 answer

Mapped provides exactly this limitation without the additional need for Length . From the documentation :

Enter a class that indicates that the result of wrapping each HList L element in the constructor of type F is Out .

Here's what it looks like in 1.2.4:

 import shapeless._ def foo[L1 <: HList, L2 <: HList](l1: L1, l2: L2)(implicit ev: MappedAux[L1, Ordering, L2] ) = () val l1 = 1 :: 1.2 :: "hello" :: HNil val l2 = Ordering[Int] :: Ordering[Double] :: Ordering[String] :: HNil val l3 = Ordering[Int] :: Ordering[Double] :: Ordering[Char] :: HNil 

And then:

 scala> foo(l1, l2) scala> foo(l1, l3) <console>:17: error: could not find implicit value for parameter ev: ... 

As expected. For 2.0, just add shapeless.ops.hlist._ import and replace MappedAux with Mapped.Aux and you are ready to go.

+9
source share

All Articles