如何在scala中合并一系列数组
How to merge a sequence of arrays in scala
我有一个 Seq[Array[Int]]
类型的值,我想以单个 Array[Int]
结束。我认为 foldLeft 会起作用,但令人惊讶的是它不起作用:
scala> val arr1 = Array(1,2,3)
arr1: Array[Int] = Array(1, 2, 3)
scala> val arr2 = Array(4,5,6)
arr2: Array[Int] = Array(4, 5, 6)
scala> val seq = Seq( arr1, arr1 )
seq: Seq[Array[Int]] = List(Array(1, 2, 3), Array(1, 2, 3))
scala> seq.foldLeft ( Array.empty )( (x,y) => x ++ y )
<console>:17: error: value ++ is not a member of Array[Nothing]
seq.foldLeft ( Array.empty )( (x,y) => x ++ y )
^
这个错误似乎并不完全正确,因为我可以这样做:
scala> Array.empty
res22: Array[Nothing] = Array()
scala> Array.empty ++ arr1 ++ arr2
res23: Array[Int] = Array(1, 2, 3, 4, 5, 6)
什么给了?
那seq.flatten.toArray
呢?
对于 foldLeft
解决方案,您应该将类型告诉编译器:Array.empty[Int]
,当您错过 [Int]
时,编译器选择 Nothing
作为 [的唯一可能类型=15=].
我有一个 Seq[Array[Int]]
类型的值,我想以单个 Array[Int]
结束。我认为 foldLeft 会起作用,但令人惊讶的是它不起作用:
scala> val arr1 = Array(1,2,3)
arr1: Array[Int] = Array(1, 2, 3)
scala> val arr2 = Array(4,5,6)
arr2: Array[Int] = Array(4, 5, 6)
scala> val seq = Seq( arr1, arr1 )
seq: Seq[Array[Int]] = List(Array(1, 2, 3), Array(1, 2, 3))
scala> seq.foldLeft ( Array.empty )( (x,y) => x ++ y )
<console>:17: error: value ++ is not a member of Array[Nothing]
seq.foldLeft ( Array.empty )( (x,y) => x ++ y )
^
这个错误似乎并不完全正确,因为我可以这样做:
scala> Array.empty
res22: Array[Nothing] = Array()
scala> Array.empty ++ arr1 ++ arr2
res23: Array[Int] = Array(1, 2, 3, 4, 5, 6)
什么给了?
那seq.flatten.toArray
呢?
对于 foldLeft
解决方案,您应该将类型告诉编译器:Array.empty[Int]
,当您错过 [Int]
时,编译器选择 Nothing
作为 [的唯一可能类型=15=].