在scala中定义2D数组

时间:2014-03-23 23:23:10

标签: arrays scala

我必须调用定义为的函数 Scala中的foo(Seq[Seq[Int]])

我已将Int数组定义为:

var myArray = Array.ofDim[Int](N,N)

我打电话给foo(myArray)

但是,我收到错误:

type mismatch;  found   : Array[Array[Int]]  required: Seq[Seq[Int]]

如果我尝试将数组定义为

var myArray = Seq[Seq[Int]](N,N)

我收到此错误:

type mismatch;  found   : Int  required: Seq[Int]

为什么?我挣扎了两个多小时,找到可能出现的问题,但我不知道......

有人可以帮我这个吗?

4 个答案:

答案 0 :(得分:2)

好吧,Array不是Seq的子类,所以这就是你得到错误的原因。

您可以将Array[Array[Int]]转换为Seq[Seq[Int]]

val myArray = Array.ofDim[Int](N,N) //use vals if you can, arrays are mutable
val mySeq = myArray.map(_.toSeq).toSeq //convert all inner Arrays to Seq and then the outer array to Seq
foo(mySeq)

请注意,Array是可变的,而Seq则不是。

答案 1 :(得分:1)

Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_45).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val N = 10
N: Int = 10

scala> val s = Seq.fill(N, N)(0)
s: Seq[Seq[Int]] = List(List(0, ... 0))

scala> 

OR

val myArray = Array.ofDim[Int](N,N)
val mySeq   = myArray.map(_.toSeq).toSeq

答案 2 :(得分:1)

方法tabulate也使用函数初始化值;例如

Seq.tabulate(2,2)( (_,_) => 0 )
Seq[Seq[Int]] = List(List(0, 0), List(0, 0))

Seq.tabulate(2,2)( _ + 2*_ )
Seq[Seq[Int]] = List(List(0, 2), List(1, 3))

Seq.tabulate(2,2)( (a,b) => (a+1)*(b+1) )
Seq[Seq[Int]] = List(List(1, 2), List(2, 4))

答案 3 :(得分:0)

如果你想要一个嵌套的seq:Seq[Seq[Int]]

  > var s = Seq(Seq(1, 2),Seq(3, 4))
  > s(0)(1)
  > 2