typelevel / algebra
1
package algebra
2
package instances
3

4
import scala.{ specialized => sp }
5

6
package object array extends ArrayInstances
7

8
trait ArrayInstances {
9
  implicit def arrayEq[@sp A: Eq]: Eq[Array[A]] =
10 0
    new ArrayEq[A]
11
  implicit def arrayOrder[@sp A: Order]: Order[Array[A]] =
12 2
    new ArrayOrder[A]
13
  implicit def arrayPartialOrder[@sp A: PartialOrder]: PartialOrder[Array[A]] =
14 0
    new ArrayPartialOrder[A]
15
}
16

17
private object ArraySupport {
18

19
  private def signum(x: Int): Int =
20 2
    if(x < 0) -1
21 2
    else if(x > 0) 1
22 2
    else 0
23

24
  def eqv[@sp A](x: Array[A], y: Array[A])(implicit ev: Eq[A]): Boolean = {
25 2
    var i = 0
26 2
    if (x.length != y.length) return false
27 2
    while (i < x.length && i < y.length && ev.eqv(x(i), y(i))) i += 1
28 2
    i == x.length
29
  }
30

31
  def compare[@sp A](x: Array[A], y: Array[A])(implicit ev: Order[A]): Int = {
32 2
    var i = 0
33 2
    while (i < x.length && i < y.length) {
34 2
      val cmp = ev.compare(x(i), y(i))
35 2
      if (cmp != 0) return cmp
36 2
      i += 1
37
    }
38 2
    signum(x.length - y.length)
39
  }
40

41
  def partialCompare[@sp A](x: Array[A], y: Array[A])(implicit ev: PartialOrder[A]): Double = {
42 0
    var i = 0
43 0
    while (i < x.length && i < y.length) {
44 0
      val cmp = ev.partialCompare(x(i), y(i))
45
      // Double.NaN is also != 0.0
46 0
      if (cmp != 0.0) return cmp
47 0
      i += 1
48
    }
49 0
    signum(x.length - y.length).toDouble
50
  }
51
}
52

53
private final class ArrayEq[@sp A: Eq] extends Eq[Array[A]] with Serializable {
54
  def eqv(x: Array[A], y: Array[A]): Boolean =
55 0
    ArraySupport.eqv(x, y)
56
}
57

58
private final class ArrayOrder[@sp A: Order]
59
  extends Order[Array[A]] with Serializable {
60
  override def eqv(x: Array[A], y: Array[A]): Boolean =
61 2
    ArraySupport.eqv(x, y)
62
  def compare(x: Array[A], y: Array[A]): Int =
63 2
    ArraySupport.compare(x, y)
64
}
65

66
private final class ArrayPartialOrder[@sp A: PartialOrder]
67
  extends PartialOrder[Array[A]] with Serializable {
68
  override def eqv(x: Array[A], y: Array[A]): Boolean =
69 0
    ArraySupport.eqv(x, y)
70
  override def partialCompare(x: Array[A], y: Array[A]): Double =
71 0
    ArraySupport.partialCompare(x, y)
72
}

Read our documentation on viewing source code .

Loading