如何在 Scala 中将函数应用于多维数组的每个元组?
我有一个二维数组,我想对数组中的每个值应用一个函数。
这是我正在处理的内容:
scala> val array = Array.tabulate(2,2)((x,y) => (0,0))
array: Array[Array[(Int, Int)]] = Array(Array((0,0), (0,0)), Array((0,0), (0,0)))
我正在使用 foreach 来提取元组:
scala> array.foreach(i => i.foreach(j => println(i)))
[Lscala.Tuple2;@11d559a
[Lscala.Tuple2;@11d559a
[Lscala.Tuple2;@df11d5
[Lscala.Tuple2;@df11d5
让我们创建一个简单的函数:
//Takes two ints and return a Tuple2. Not sure this is the best approach.
scala> def foo(i: Int, j: Int):Tuple2[Int,Int] = (i+1,j+2)
foo: (i: Int,j: Int)(Int, Int)
它可以运行,但需要应用于数组(如果可变)或返回新数组。
scala> array.foreach(i => i.foreach(j => foo(j._1, j._2)))
应该不会太差吧我认为我缺少一些基础知识......
I've got a two dimensional array and I want to apply a function to each value in the array.
Here's what I'm working with:
scala> val array = Array.tabulate(2,2)((x,y) => (0,0))
array: Array[Array[(Int, Int)]] = Array(Array((0,0), (0,0)), Array((0,0), (0,0)))
I'm using foreach to extract the tuples:
scala> array.foreach(i => i.foreach(j => println(i)))
[Lscala.Tuple2;@11d559a
[Lscala.Tuple2;@11d559a
[Lscala.Tuple2;@df11d5
[Lscala.Tuple2;@df11d5
Let's make a simple function:
//Takes two ints and return a Tuple2. Not sure this is the best approach.
scala> def foo(i: Int, j: Int):Tuple2[Int,Int] = (i+1,j+2)
foo: (i: Int,j: Int)(Int, Int)
This runs, but need to apply to array(if mutable) or return new array.
scala> array.foreach(i => i.foreach(j => foo(j._1, j._2)))
Shouldn't be to bad. I'm missing some basics I think...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(更新:删除了不正确的 for 理解代码 - 它返回一个一维数组)
应用于可变数组
(UPDATE: removed the for comprehension code which was not correct - it returned a one dimensional array)
To apply to a mutable array
例如
强制需要点符号
e.g.
Dot notation required to force