Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method that returns List of size n in Shapeless

Is it possible to make the following code work?

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 compile error saying "could not find implicit value for parameter toIntN: shapeless.ToInt[N]".

like image 972
Kim Stebel Avatar asked Aug 07 '12 15:08

Kim Stebel


Video Answer


1 Answers

You can just add a context bound:

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

Which 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 the following using 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+ ) )
}
like image 162
Travis Brown Avatar answered Sep 24 '22 20:09

Travis Brown