scala 关于Scala元组的简单问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3343934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple question about tuple of scala
提问by Freewind
I'm new to scala, and what I'm learning is tuple.
我是 Scala 的新手,我正在学习的是tuple.
I can define a tuple as following, and get the items:
我可以定义一个元组如下,并获得项目:
val tuple = ("Mike", 40, "New York")
println("Name: " + tuple._1)
println("Age: " + tuple._2)
println("City: " + tuple._3)
My question is:
我的问题是:
- How to get the length of a tuple?
- Is tuple mutable? Can I modify its items?
- Is there any other useful operation we can do on a tuple?
- 如何获得元组的长度?
- 元组是可变的吗?我可以修改它的项目吗?
- 我们可以对元组进行任何其他有用的操作吗?
Thanks in advance!
提前致谢!
回答by missingfaktor
1] tuple.productArity
1] tuple.productArity
2] No.
2] 没有。
3] Some interesting operations you can perform on tuples: (a short REPL session)
3] 你可以对元组执行一些有趣的操作:(一个简短的 REPL 会话)
scala> val x = (3, "hello")
x: (Int, java.lang.String) = (3,hello)
scala> x.swap
res0: (java.lang.String, Int) = (hello,3)
scala> x.toString
res1: java.lang.String = (3,hello)
scala> val y = (3, "hello")
y: (Int, java.lang.String) = (3,hello)
scala> x == y
res2: Boolean = true
scala> x.productPrefix
res3: java.lang.String = Tuple2
scala> val xi = x.productIterator
xi: Iterator[Any] = non-empty iterator
scala> while(xi.hasNext) println(xi.next)
3
hello
回答by olle kullberg
One thing that you can also do with a tuple is to extract the content using the matchexpression:
您还可以使用元组做的一件事是使用match表达式提取内容:
def tupleview( tup: Any ){
tup match {
case (a: String, b: String) =>
println("A pair of strings: "+a + " "+ b)
case (a: Int, b: Int, c: Int) =>
println("A triplet of ints: "+a + " "+ b + " " +c)
case _ => println("Unknown")
}
}
tupleview( ("Hello", "Freewind"))
tupleview( (1,2,3))
Gives:
给出:
A pair of strings: Hello Freewind
A triplet of ints: 1 2 3
回答by retronym
Tuplesare immutable, but, like all cases classes, they have a copy method that can be used to create a new Tuplewith a few changed elements:
Tuples是不可变的,但是,像所有 case 类一样,它们有一个复制方法,可用于创建一个Tuple具有一些更改元素的新元素:
scala> (1, false, "two")
res0: (Int, Boolean, java.lang.String) = (1,false,two)
scala> res0.copy(_2 = true)
res1: (Int, Boolean, java.lang.String) = (1,true,two)
scala> res1.copy(_1 = 1f)
res2: (Float, Boolean, java.lang.String) = (1.0,true,two)
回答by Landei
Concerning question 3:
关于问题3:
A useful thing you can do with Tuples is to store parameter lists for functions:
你可以用元组做的一个有用的事情是存储函数的参数列表:
def f(i:Int, s:String, c:Char) = s * i + c
List((3, "cha", '!'), (2, "bora", '.')).foreach(t => println((f _).tupled(t)))
//--> chachacha!
//--> borabora.
[Edit] As Randall remarks, you'd better use something like this in "real life":
[编辑] 正如兰德尔所说,你最好在“现实生活”中使用这样的东西:
def f(i:Int, s:String, c:Char) = s * i + c
val g = (f _).tupled
List((3, "cha", '!'), (2, "bora", '.')).foreach(t => println(g(t)))
In order to extract the values from tuples in the middle of a "collection transformation chain" you can write:
为了从“集合转换链”中间的元组中提取值,您可以编写:
val words = List((3, "cha"),(2, "bora")).map{ case(i,s) => s * i }
Note the curly braces around the case, parentheses won't work.
注意案例周围的花括号,括号不起作用。
回答by Sandor Murakozi
Another nice trick ad question 3) (as 1 and 2 are already answered by others)
另一个不错的技巧广告问题 3)(因为其他人已经回答了 1 和 2)
val tuple = ("Mike", 40, "New York")
tuple match {
case (name, age, city) =>{
println("Name: " + name)
println("Age: " + age)
println("City: " + city)
}
}
Edit: in fact it's rather a feature of pattern matching and case classes, a tuple is just a simple example of a case class...
编辑:实际上它是模式匹配和案例类的一个特征,元组只是案例类的一个简单例子......
回答by Jesper
1 and 2 have already been answered.
1和2已经回答了。
A very useful thing that you can use tuples for is to return more than one value from a method or function. Simple example:
可以使用元组的一件非常有用的事情是从方法或函数返回多个值。简单的例子:
// Get the min and max of two integers
def minmax(a: Int, b: Int): (Int, Int) = if (a < b) (a, b) else (b, a)
// Call it and assign the result to two variables like this:
val (x, y) = minmax(10, 3) // x = 3, y = 10
回答by sepp2k
- You know the size of a tuple, it's part of it's type. For example if you define a function
def f(tup: (Int, Int)), you know the length oftupis 2 because values of type(Int, Int)(akaTuple2[Int, Int]) always have a length of 2. - No.
- Not really. Tuples are useful for storing a fixed amount of items of possibly different types and passing them around, putting them into data structures etc. There's really not much you can do with them, other than creating tuples, and getting stuff out of tuples.
- 您知道元组的大小,它是其类型的一部分。例如,如果您定义了一个函数
def f(tup: (Int, Int)),则您知道 的长度tup为 2,因为类型(Int, Int)(又名Tuple2[Int, Int])的值的长度始终为 2。 - 不。
- 并不真地。元组对于存储固定数量的可能不同类型的项目并传递它们、将它们放入数据结构等很有用。除了创建元组和从元组中取出东西之外,你真的没有什么可以做的。
回答by Alex Archambault
Using shapeless, you easily get a lot of useful methods, that are usually available only on collections:
使用shapeless,您可以轻松获得许多有用的方法,这些方法通常仅适用于集合:
import shapeless.syntax.std.tuple._
val t = ("a", 2, true, 0.0)
val first = t(0)
val second = t(1)
// etc
val head = t.head
val tail = t.tail
val init = t.init
val last = t.last
val v = (2.0, 3L)
val concat = t ++ v
val append = t :+ 2L
val prepend = 1.0 +: t
val take2 = t take 2
val drop3 = t drop 3
val reverse = t.reverse
val zip = t zip (2.0, 2, "a", false)
val (unzip, other) = zip.unzip
val list = t.toList
val array = t.toArray
val set = t.to[Set]
Everything is typed as one would expect (that is firsthas type String, concathas type (String, Int, Boolean, Double, Double, Long), etc.)
一切都按预期输入(即first具有 type String,concat具有 type(String, Int, Boolean, Double, Double, Long)等)
The last method above (.to[Collection]) should be available in the next release (as of 2014/07/19).
上面的最后一个方法 ( .to[Collection]) 应该在下一个版本中可用(截至 2014/07/19)。
You can also "update" a tuple
你也可以“更新”一个元组
val a = t.updatedAt(1, 3) // gives ("a", 3, true, 0.0)
but that will return a new tuple instead of mutating the original one.
但这将返回一个新元组而不是改变原始元组。

