Method that returns List of size n in Shapeless

Is it possible to make the following code?

def zeroTo[N <: Nat]:Sized[List[Int], N] = { new Sized[List[Int], N](List.iterate(0, toInt[N])(1+)) { type A = Int } } 

I get a compilation error: "could not find the implicit value of the parameter toIntN: shapeless.ToInt [N]".

+7
source share
1 answer

You can simply add context binding:

 def zeroTo[N <: Nat: ToInt]: Sized[List[Int], N] = { new Sized[List[Int], N](List.iterate(0, toInt[N])(1+)) { type A = Int } } 

What gives us:

 scala> zeroTo[_6] res0: shapeless.Sized[List[Int],shapeless.Nat._6] = List(0, 1, 2, 3, 4, 5) 

Note that you can write this more or less equivalently as follows: wrap :

 def zeroTo[N <: Nat: ToInt]: Sized[List[Int], N] = Sized.wrap(List.iterate(0, toInt[N])(1+)) 

Update: version for Shapeless 2.2.0:

 def zeroTo[N <: Nat: ToInt]: Sized[List[Int], N] = { Sized.wrap[List[Int], N]( List.iterate( 0, toInt[N] )( 1+ ) ) } 
+9
source

All Articles