diff options
author | Simon Ochsenreither <simon@ochsenreither.de> | 2011-12-02 15:29:51 +0100 |
---|---|---|
committer | Simon Ochsenreither <simon@ochsenreither.de> | 2011-12-02 15:36:03 +0100 |
commit | db7bd31896231cbb8f018ffd8a82bc956d066e40 (patch) | |
tree | de45d4f3d9520724f901f25dc143ab041c7d31ba /src | |
parent | 947797ea23d711e501605c0cc218fec88e3b97ef (diff) | |
download | scala-db7bd31896231cbb8f018ffd8a82bc956d066e40.tar.gz scala-db7bd31896231cbb8f018ffd8a82bc956d066e40.tar.bz2 scala-db7bd31896231cbb8f018ffd8a82bc956d066e40.zip |
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.
Diffstat (limited to 'src')
-rw-r--r-- | src/library/scala/collection/immutable/Range.scala | 7 |
1 files changed, 7 insertions, 0 deletions
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 |