0

How to add multiple items to HList?

My naive version doesn't compile:

(1 to 100).foldLeft(HNil)((l,i) => i :: l)

For ordinary Lists this approach would work well. For HList, however, I assume, it's required to provide a Poly2 that takes a single item and a HList and returns the appended list.

Of course, if there are any better ways to add multiple item, those approaches would be very appreciated.

  • What would be the type of the result ? – Cyrille Corpet Mar 23 '17 at 00:04
  • @CyrilleCorpet A HList with only Ints, so I guess it would be Int::...::Int::HNil (sure, in this simple example I could use an ordinary list, but my real use case is more complex and I'm already failing at this initial step.) – Nepomuk Hirsch Mar 23 '17 at 07:49
  • How can `foldLeft` return a type that depends on the length of the list on which it is applied? Your problem is that you want to transform dynamic information (the length of your range) into static information (the length of the `HList`, which is encoded in its type). You won't be able to do it. – Cyrille Corpet Mar 23 '17 at 08:38
  • Maybe you should try going for a [sized](https://github.com/milessabin/shapeless/blob/master/core/src/main/scala/shapeless/sized.scala) collection. You can simply convert them to an `HList`. – Jasper-M Mar 23 '17 at 09:03

1 Answers1

0

This is probably an XY problem. But what you are trying to do here could be done with a Sized collection.

scala> import shapeless._, syntax.sized._
import shapeless._
import syntax.sized._

scala> (1 to 10).reverse.toList.ensureSized[nat._10].toHList
res1: shapeless.::[Int,shapeless.::[Int,shapeless.::[Int,shapeless.::[Int,shapeless.::[Int,shapeless.::[Int,shapeless.::[Int,shapeless.::[Int,shapeless.::[Int,shapeless.::[Int,shapeless.HNil]]]]]]]]]] = 10 :: 9 :: 8 :: 7 :: 6 :: 5 :: 4 :: 3 :: 2 :: 1 :: HNil

If you want a range of 100 you have the problem that nat._100 doesn't exist, so you have to create that yourself. I would just calculate it:

val prod = the[ops.nat.Prod[nat._10, nat._10]]
type _100 = prod.Out
(1 to 100).reverse.toList.ensureSized[_100].toHList
Jasper-M
  • 14,966
  • 2
  • 26
  • 37
  • Yes, your right, it's a XY problem, thanks for the hint. What I simply want to achieve is to add a few thousands elements to conduct some simple benchmarks (as I want to use the HList a simple heterogeneous map without any need for implicits etc, this, however, has the drawback of O(n) read access, hence I want benchmark it). – Nepomuk Hirsch Mar 25 '17 at 11:57