英文:
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)})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论