I am trying to slice a tuple, removing the last two items. I tried using the list drop/take methods but I can’t succeed to get a tuple back.
Here is the approach I tried :
scala> val myTuple = (1, 2, 4, 5, 0, 5)
myTuple: (Int, Int, Int, Int, Int, Int) = (1,2,4,5,0,5)
scala> val myList = myTuple.productIterator.toList
myList: List[Any] = List(1, 2, 4, 5, 0, 5)
scala> val mySubList = myList.dropRight(2)
mySubList: List[Any] = List(1, 2, 4, 5)
scala> val mySubTuple = ???
I saw here that list to tuple isn’t (yet?) possible in scala.
Are there other ways to get that subtuple (without dealing with myTuple._1, myTuple._2…) ?
This is the sort of thing that shapeless can do in a generic way, involving conversion into an
HList.First – get shapeless. Then run scala with dependent method types switched on (on by default in 2.10):
Add shapeless to the classpath:
Now let us play!
We must import shapeless
We turn our tuple into an
HListThen we take the first 4 (notice that
_4is a type parameter, not a method argument)Now convert back to a tuple
We could shorten this:
This of course generalizes to the first
Melements of anN-tuple