Changes list so it doesn't check length at each stage in the equality test. default tip
authorDavid R. MacIver@DRM-DESKTOP.trampolan
Tue Apr 29 15:03:21 2008 +0100 (8 months ago)
changeset 13f91763b1ec29
parent 12c8920a9d795d
Changes list so it doesn't check length at each stage in the equality test.
--- a/perftests.scala Wed May 21 15:16:37 2008 +0100
+++ b/perftests.scala Tue Apr 29 15:03:21 2008 +0100
@@ -37,6 +37,10 @@ object Main{
Traversable.fromIterable(List.range(1, size)).map((_ : Int) * 2).as[List, Int],
List.range(1, size).map( (_ : Int) * 2))
+ test("map over custom lists",
+ Traversable.range(1, size).as[sequence.List, Int].map((_ : Int) * 2).as[sequence.List, Int],
+ List.range(1, size).map( (_ : Int) * 2))
+
test("map over arrays",
Traversable.fromArray(Array.range(1, size)).map((_ : Int) * 2).as[Array, Int],
Array.range(1, size).map( (_ : Int) * 2)
@@ -48,6 +52,6 @@ object Main{
test("filter over arrays",
Traversable.fromArray(Array.range(1, size)).filter( (x : Int) => x % 2 == 0).as[Array, Int],
- Array.range(1, size).filter( (x : Int) => x % 2 == 0))
+ Array.range(1, size).filter( (x : Int) => x % 2 == 0))
}
}
--- a/src/main/scala/sequence/list.scala Wed May 21 15:16:37 2008 +0100
+++ b/src/main/scala/sequence/list.scala Tue Apr 29 15:03:21 2008 +0100
@@ -38,11 +38,14 @@ object List extends SequenceType{
if (this eq that.asInstanceOf[AnyRef]) true
else that match {
case (that : List[_]) => if (that.length != this.length) false;
- else if (this.isEmpty) true;
- else if (this.head != that.head) false;
- else this.tail.equals(that.tail);
+ else equalsSameLength(that);
case _ => false;
+ }
+
+ private final def equalsSameLength(that : List[_]) = this match {
+ case Nil => true;
+ case (x :: xs) => if (x != that.head) false else this.tail == that.tail
}
override final def hashCode = hash(0);
--- a/src/main/scala/traversable.scala Wed May 21 15:16:37 2008 +0100
+++ b/src/main/scala/traversable.scala Tue Apr 29 15:03:21 2008 +0100
@@ -162,6 +162,18 @@ object Traversable{
}
}
+ def fromArray[T](it : Array[T]) = new Traversable[T]{
+ def traverse(f : T => Unit) = {
+ var i = 0;
+ while (i < it.length) {
+ f(it(i));
+ i = i + 1;
+ }
+ }
+
+ override def knownSize = Some(it.length);
+ }
+
val empty = new Traversable[Nothing]{
def traverse(f : Nothing => Unit) { }
}
@@ -193,7 +205,8 @@ object Traversable{
}
override def take(n : Int) = range(from, Math.min(from + n, until));
- override def drop(n : Int) = range(from + n, until);
+ override def drop(n : Int) = range(from + n, until);
+ override def knownSize = until - from;
}
def break = throw Break;