如何在 Scala 中将函数应用于多维数组的每个元组?

发布于 2024-09-27 05:43:17 字数 832 浏览 1 评论 0原文

我有一个二维数组,我想对数组中的每个值应用一个函数。

这是我正在处理的内容:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

断桥再见 2024-10-04 05:43:17

(更新:删除了不正确的 for 理解代码 - 它返回一个一维数组)

def foo(t: (Int, Int)): (Int, Int) = (t._1 + 1, t._2 + 1)
array.map{_.map{foo}}

应用于可变数组

val array = ArrayBuffer.tabulate(2,2)((x,y) => (0,0))
for (sub <- array; 
     (cell, i) <- sub.zipWithIndex) 
  sub(i) = foo(cell._1, cell._2)

(UPDATE: removed the for comprehension code which was not correct - it returned a one dimensional array)

def foo(t: (Int, Int)): (Int, Int) = (t._1 + 1, t._2 + 1)
array.map{_.map{foo}}

To apply to a mutable array

val array = ArrayBuffer.tabulate(2,2)((x,y) => (0,0))
for (sub <- array; 
     (cell, i) <- sub.zipWithIndex) 
  sub(i) = foo(cell._1, cell._2)
此刻的回忆 2024-10-04 05:43:17
2dArray.map(_.map(((_: Int).+(1) -> (_: Int).+(1)).tupled))

例如

scala> List[List[(Int, Int)]](List((1,3))).map(_.map(((_: Int).+(1) -> (_: Int).+(1)).tupled))
res123: List[List[(Int, Int)]] = List(List((2,4)))

强制需要点符号

2dArray.map(_.map(((_: Int).+(1) -> (_: Int).+(1)).tupled))

e.g.

scala> List[List[(Int, Int)]](List((1,3))).map(_.map(((_: Int).+(1) -> (_: Int).+(1)).tupled))
res123: List[List[(Int, Int)]] = List(List((2,4)))

Dot notation required to force

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文