PageRenderTime 51ms CodeModel.GetById 28ms app.highlight 18ms RepoModel.GetById 1ms app.codeStats 0ms

/core/src/main/scala/scalaz/Ordering.scala

http://github.com/scalaz/scalaz
Scala | 82 lines | 65 code | 11 blank | 6 comment | 22 complexity | cb57f68d04138cdf17f067d2498d22f1 MD5 | raw file
 1package scalaz
 2
 3/** A ternary marker of how two values relate in an ordering.
 4  *
 5  * @note scalaz calls its version of [[scala.math.Ordering]],
 6  *       [[scalaz.Order]].  This `Ordering` is analogous to the
 7  *       `Int`s returned by [[scala.math.Ordering]].
 8  */
 9sealed abstract class Ordering(val toInt: Int, val name: String) extends Product with Serializable {
10  def complement: Ordering
11}
12
13object Ordering extends OrderingInstances {
14  case object LT extends Ordering(-1, "LT") { def complement = GT }
15  case object EQ extends Ordering(0,  "EQ") { def complement = EQ }
16  case object GT extends Ordering(1,  "GT") { def complement = LT }
17
18  def fromLessThan[A](a1: A, a2: A)(f: (A, A) => Boolean): Ordering =
19    if (f(a1, a2)) LT
20    else if (f(a2, a1)) GT
21    else EQ
22
23  def fromInt(intOrdering: Int): Ordering = if (intOrdering < 0) LT else if (intOrdering > 0) GT else EQ
24}
25
26sealed abstract class OrderingInstances {
27
28  import Ordering._
29
30  implicit val orderingInstance: Enum[Ordering] with Show[Ordering] with Monoid[Ordering] = new Enum[Ordering] with Show[Ordering] with Monoid[Ordering] {
31    def order(a1: Ordering, a2: Ordering): Ordering = (a1, a2) match {
32      case (LT, LT)      => EQ
33      case (LT, EQ | GT) => LT
34      case (EQ, LT)      => GT
35      case (EQ, EQ)      => EQ
36      case (EQ, GT)      => LT
37      case (GT, LT | EQ) => GT
38      case (GT, GT)      => EQ
39    }
40
41    override def show(f: Ordering): Cord = Cord(shows(f))
42    override def shows(f: Ordering) = f.name
43
44    def append(f1: Ordering, f2: => Ordering): Ordering = f1 match {
45      case Ordering.EQ => f2
46      case o           => o
47    }
48
49    def zero: Ordering = Ordering.EQ
50
51    def succ(b: Ordering) = b match {
52      case Ordering.LT => Ordering.EQ
53      case Ordering.EQ => Ordering.GT
54      case Ordering.GT => Ordering.LT
55    }
56    def pred(b: Ordering) = b match {
57      case Ordering.GT => Ordering.EQ
58      case Ordering.EQ => Ordering.LT
59      case Ordering.LT => Ordering.GT
60    }
61    override def succn(a: Int, b: Ordering) =
62      if(a < 0)
63        predn(-a, b)
64      else if(a % 3 == 0)
65        b
66      else if(a % 3 == 1)
67        succ(b)
68      else
69        succ(succ(b))
70    override def predn(a: Int, b: Ordering) =
71      if(a < 0)
72        succn(-a, b)
73      else if(a % 3 == 0)
74        b
75      else if(a % 3 == 1)
76        pred(b)
77      else
78        pred(pred(b))
79    override def min = Some(LT)
80    override def max = Some(GT)
81  }
82}