【问题标题】:Swapping two vars in scala [duplicate]在scala中交换两个变量[重复]
【发布时间】:2011-10-02 07:01:28
【问题描述】:

可能重复:
Tuple parameter declaration and assignment oddity

在python中我可以做到

>>> (a,b) = (1,2)
>>> (b,a) = (a,b)
>>> (a,b)
(2, 1)

但在 scala 中:

Welcome to Scala version 2.8.1.final (OpenJDK Server VM, Java 1.6.0_20).
Type in expressions to have them evaluated.
Type :help for more information.

scala> var (a,b) = (1,2)
a: Int = 1
b: Int = 2

scala> (a,b)=(b,a)
<console>:1: error: ';' expected but '=' found.
       (a,b)=(b,a)
            ^

所以虽然我可以将 vars 初始化为一个元组,但我不能将它们分配为一个元组。除了使用 tmp var,还有什么办法可以解决这个问题?

【问题讨论】:

标签: scala functional-programming


【解决方案1】:

这是 Scala 2.9.0.1

scala> val pair = (1,2)
pair: (Int,Int) = (1,2)

scala> val swappedPair = pair.swap
swappedPair: (Int,Int) = (2,1)

方法swap 生成另一个元组而不是更改旧的元组,我不知道它是否已经存在于 Scala 2.8.1 中。

【讨论】:

  • 是的,它在 2.8 中有,但这只返回一个交换的元组。所以没有解决vars的id交换问题。
【解决方案2】:

不幸的是,没有简单的方法。表达式(a,b) 构造了一个Tuple[Int, Int] 类型的不可变对象。在这个元组中,ab 的身份作为可变的vars 丢失了。前两个问题可能会提供更多信息:

Tuple parameter declaration and assignment oddity

Is it possible to have tuple assignment to variables in Scala?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2017-11-10
    • 1970-01-01
    • 2013-04-18
    • 2023-02-04
    • 1970-01-01
    相关资源
    最近更新 更多