From db7bd31896231cbb8f018ffd8a82bc956d066e40 Mon Sep 17 00:00:00 2001 From: Simon Ochsenreither Date: Fri, 2 Dec 2011 15:29:51 +0100 Subject: Makes Range#sum an O(1) operation instead of an O(n) one. Partially fixes SI-4658. NumericRange stays slow, thanks to the brilliant idea that Numeric doesn't need a division operation. --- src/library/scala/collection/immutable/Range.scala | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src') diff --git a/src/library/scala/collection/immutable/Range.scala b/src/library/scala/collection/immutable/Range.scala index 47ce2f0341..3736096f36 100644 --- a/src/library/scala/collection/immutable/Range.scala +++ b/src/library/scala/collection/immutable/Range.scala @@ -211,6 +211,13 @@ extends collection.AbstractSeq[Int] final def contains(x: Int) = isWithinBoundaries(x) && ((x - start) % step == 0) + final override def sum[B >: Int](implicit num: Numeric[B]): Int = { + val len = length + if (len == 0) 0 + else if (len == 1) head + else (len.toLong * (head + last) / 2).toInt + } + override def toIterable = this override def toSeq = this -- cgit v1.2.3