Fix and test for #2446.

git-svn-id: http://lampsvn.epfl.ch/svn-repos/scala/scala/trunk@19183 5e8d7ff9-d8ef-0310-90f0-a4852d11357a
This commit is contained in:
phaller 2009-10-21 10:08:34 +00:00
parent 865bf27f75
commit d927529a38
3 changed files with 22 additions and 16 deletions

View File

@ -13,6 +13,7 @@ package scala.collection
import generic._
import mutable.ArrayBuffer
import scala.annotation.tailrec
/** Sequences that support O(1) element access and O(1) length computation.
* This class does not add any methods to Seq but overrides several
@ -77,27 +78,22 @@ trait VectorLike[+A, +Repr] extends SeqLike[A, Repr] { self =>
if (i < length) Some(this(i)) else None
}
private def foldl[B](start: Int, z: B, op: (B, A) => B): B = {
var i = start
val len = length
var result = z
while (i < len) {
result = op(result, this(i))
i += 1
}
result
}
private def foldr[B](start: Int, len: Int, z: B, op: (A, B) => B): B =
if (start == len) z
else op(this(start), foldr(start + 1, len, z, op))
@tailrec
private def foldl[B](start: Int, end: Int, z: B, op: (B, A) => B): B =
if (start == end) z
else foldl(start + 1, end, op(z, this(start)), op)
@tailrec
private def foldr[B](start: Int, end: Int, z: B, op: (A, B) => B): B =
if (start == end) z
else foldr(start, end - 1, op(this(end - 1), z), op)
override def foldLeft[B](z: B)(op: (B, A) => B): B =
foldl(0, z, op)
foldl(0, length, z, op)
override def foldRight[B](z: B)(op: (A, B) => B): B =
foldr(0, length, z, op)
override def reduceLeft[B >: A](op: (B, A) => B): B =
if (length > 0) foldl(1, this(0), op) else super.reduceLeft(op)
if (length > 0) foldl(1, length, this(0), op) else super.reduceLeft(op)
override def reduceRight[B >: A](op: (A, B) => B): B =
if (length > 0) foldr(0, length - 1, this(length - 1), op) else super.reduceRight(op)

View File

@ -0,0 +1 @@
3

View File

@ -0,0 +1,9 @@
object Test {
def main(args : Array[String]) : Unit = {
val arr = new Array[Int](10000)
arr(5000) = 1
arr (9000) = 2
val sum = arr.reduceRight(_ + _)
println(sum)
}
}