操作元组 [英] Manipulating tuples

查看:47
本文介绍了操作元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在不使用临时变量和启动新语句的情况下操作元组的多个值?

Is there a way to manipulate multiple values of a tuple without using a temporary variable and starting a new statement?

假设我有一个返回元组的方法,我想对这些值进行内联处理.

Say I have a method that returns a tuple and I want to do something with those values inline.

例如如果我想在某个点拆分一个字符串并反转片段

e.g. if I want to split a string at a certain point and reverse the pieces

def backToFront(s: String, n:Int) = s.splitAt(n)...

我能做到

val (a, b) = s.splitAt(n)
b + a 

(需要临时变量和新语句)或

(requires temporary variables and new statement) or

List(s.splitAt(n)).map(i => i._2 + i._1).head

(有效,但看起来有点脏,为此创建了一个元素列表)或

(works, but seems a bit dirty, creating a single element List just for this) or

s.splitAt(n).swap.productIterator.mkString

(适用于这个特定示例,但只是因为碰巧有一个 swap 方法可以执行我想要的操作,所以它不是很通用).

(works for this particular example, but only because there happens to be a swap method that does what I want, so it's not very general).

元组上的 zipped 方法似乎只是用于列表元组.

The zipped method on tuples seems just to be for tuples of Lists.

再举个例子,你怎么能把元组 ('a, 'b, 'c) 变成 ('b, 'a, 'c) ?声明?

As another example, how could you turn the tuple ('a, 'b, 'c) into ('b, 'a, 'c) in one statement?

推荐答案

元组只是方便的返回类型,并不假设你会用它进行复杂的操作.在 Scala 论坛上也有类似的讨论.

Tuples are just convenient return type, and it is not assumed that you will make complicated manipulations with it. Also there was similar discussion on scala forums.

关于最后一个例子,找不到比模式匹配更好的了.

About the last example, couldn't find anything better than pattern-matching.

('a, 'b, 'c) match { case (a, b, c) => (b, a ,c) }

这篇关于操作元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆