使用包含嵌套IndexedSeq的映射一次初始化变量

时间:2012-03-23 12:54:43

标签: scala functional-programming sequence

我搜索方法来解决tuple()的初始化问题与地图的结果,如下所示:

//My current state of cities
val listOfCity = IndexedSeq(new City1(), new City2())

// Function which compute my new state
val (newCity,exchange) = listOfCity.map{ city =>  computeNewCity(city,listOfCity)}    

变量newCity包含computeNewCity()返回的元组的结果._1,变量exchange包含相同元组的结果._2。

函数computeNewCity()返回我的对象​​城市的新版本和交换历史,我与listOfCity中其他城市交换的结果,它是(City, Exchange)类型的元组

如何在功能编程的帮助下实现这一目标?

谢谢! SR

2 个答案:

答案 0 :(得分:2)

问题是listOfCity.map{ city => computeNewCity(city,listOfCity)}返回IndexedSeq[(City, Exchange)]listOfCity中每个城市的一个元组),显然你不能将它分配给(City, Exchange)元组。你可以采取第一个元素或最后一个元素:

val (firstCity,exchange) = listOfCity.map{ city =>  computeNewCity(city,listOfCity)}.first

val (lastCity,exchange) = listOfCity.map{ city =>  computeNewCity(city,listOfCity)}.last

或获得两个序列的元组(城市及其相应的交换)

val (cities,exchanges) = listOfCity.map{ city =>  computeNewCity(city,listOfCity)}.unzip

答案 1 :(得分:1)

这是你想要做的吗?

scala> val Seq(a, b) =  IndexedSeq(IndexedSeq(3.0,2.0), IndexedSeq(1.0))
a: IndexedSeq[Double] = Vector(3.0, 2.0)
b: IndexedSeq[Double] = Vector(1.0)