如何在scala中切片元组

时间:2012-06-19 09:32:51

标签: scala

我正在尝试切片一个元组,删除最后两个项目。我尝试使用list drop / take方法但我无法成功获得元组。

这是我尝试过的方法:

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 = ???

我看到here列表中的元组在scala中是不可能的(但是?)。

是否有其他方法可以获得该子组(不处理myTuple._1,myTuple._2 ......)?

3 个答案:

答案 0 :(得分:40)

这是shapeless可以用泛型方式执行的操作,涉及转换为HList

首先 - get shapeless。然后运行scala并打开依赖方法类型(默认情况下在2.10中启用):

C:\Scala\sdk\scala-2.9.2\bin>scala -Ydependent-method-types
Welcome to Scala version 2.9.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_04).
Type in expressions to have them evaluated.
Type :help for more information.

在类路径中添加无形:

scala> :cp C:\Users\cmarsha\Downloads\shapeless_2.9.2-1.2.2.jar
Added 'C:\Users\cmarsha\Downloads\shapeless_2.9.2-1.2.2.jar'.  Your new classpath is:
"C:\tibco\tibrv\8.2\lib\tibrvnative.jar;C:\Users\cmarsha\Downloads\shapeless_2.9.2-1.2.2.jar"

现在让我们玩吧!

scala> (1, 2.3, 'a, 'b', "c", true)
res0: (Int, Double, Symbol, Char, java.lang.String, Boolean) = (1,2.3,'a,b,c,true)

我们必须导入无形

scala> import shapeless._; import Tuples._; import Nat._
import shapeless._
import Tuples._
import Nat._

我们将元组转换为HList

scala> res0.hlisted
res2: shapeless.::[Int,shapeless.::[Double,shapeless.::[Symbol,shapeless.::[Char,shapeless.::[java.lang.String,shapeless.::[Boolean,shapeless.HNil]]]]]] = 1 :: 2.3 :: 'a :: b :: c :: true :: HNil

然后我们取第4个(注意_4是类型参数,不是方法参数

scala> res2.take[_4]
res4: shapeless.::[Int,shapeless.::[Double,shapeless.::[Symbol,shapeless.::[Char, shapeless.HNil]]]] = 1 :: 2.3 :: 'a :: b :: HNil

现在转换回元组

scala> res4.tupled
res5: (Int, Double, Symbol, Char) = (1,2.3,'a,b)

我们可以缩短这个:

val (a, b, c, d) = sixtuple.hlisted.take[_4].tupled 
//a, b, c and d would all have the correct inferred type

这当然会推广到M - 元组的第一个N元素

答案 1 :(得分:5)

scala> val myTuple = (1, 2, 4, 5, 0, 5)
myTuple: (Int, Int, Int, Int, Int, Int) = (1,2,4,5,0,5)

scala> myTuple match {
     |   case (a, b, c, d, _, _) => (a, b, c, d)
     | }
res0: (Int, Int, Int, Int) = (1,2,4,5)

答案 2 :(得分:5)

怎么样:


scala> val myTuple = (1,2,4,5,0,5)
myTuple: (Int, Int, Int, Int, Int, Int) = (1,2,4,5,0,5)

scala> val (left,right):Tuple2[List[Int],List[Int]] = myTuple.productIterator.toList.splitAt(myTuple.productArity - 2)
left: List[Int] = List(1, 2, 4, 5)
right: List[Int] = List(0, 5)

scala> val mytuple2 = (right(0),right(1))
mytuple2: (Int, Int) = (0,5)