更新带有 .map 功能的 Scala 不可变序列。

huangapple go评论79阅读模式
英文:

Updating scala immutable SEQ with .map functionality

问题

我正在为大学的俄罗斯方块作业而努力,其中必须使用不可变的数据结构。

问题

我尝试的是使用seq.map函数遍历序列的所有值,并根据旧值替换为新值。由于某种原因,这与我在网上看到的示例不同。我做错了什么?

class Point(x: Int, y: Int) {

}

val bodyPosition: Seq[Point] = Seq[Point](new Point(-1, 0), new Point(0, 0), new Point(1, 0), new Point(2, 0))
bodyPosition.map(map => { new Point(-map.y, map.x) })

序列内部的数据保持不变。

英文:

I am working on a Tetris assignment for university where it is obligatory to use an immutable data structure.

Question

What I am trying to do is use the seq.map function to go through all the values of the seq and replace them with new ones based on the old ones. For some reason this does not work the same as examples I have seen online. What am I doing wrong?

class Point(x : Int, y : Int) {

}

val bodyPosition: Seq[Point] = Seq[Point](new Point(-1,0), new Point(0,0), new Point(1,0), new Point(2,0))
bodyPosition.map(map => {new Point(-map.y, map.x)})

The data inside the seq stays the same.

答案1

得分: 0

"是的,因为它是不可变的,这就是重点。但是,如果你仔细查看文档,你会看到map会返回一个新的集合,所以你只需要将其赋值给某个变量即可。 – 路易斯·米格尔·梅希亚·苏亚雷斯"

base class Point(x : Int, y : Int){}

class Gamelogic(){
  val bodyPosition: Seq[Point] = Seq[Point](new Point(-1,0),
             new Point(0,0), new Point(1,0), new Point(2,0))
        
  val newBodyPosition = bodyPosition.map(map => {new Point(-map.y, map.x)})
}
英文:

"Yeah because it is immutable, that is the point. But, if you look close to the documentation you will see that map returns a new collection, so you simply have to assign that to some variable –Luis Miguel Mejía Suárez"

base class Point(x : Int, y : Int){}

class Gamelogic(){
  val bodyPosition: Seq[Point] = Seq[Point](new Point(-1,0),
             new Point(0,0), new Point(1,0), new Point(2,0))
        
  val newBodyPosition = bodyPosition.map(map => {new Point(-map.y, map.x)})
}

huangapple
  • 本文由 发表于 2020年9月27日 20:46:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64088627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定