Last active
August 7, 2022 12:05
-
-
Save TheDIM47/21dd12506f77ddc0a608fb5cb118be6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.math.Ordering.Implicits.infixOrderingOps | |
/** simple interval [min, max) (or >= min if max is empty) */ | |
final class Interval[A](val min: A, val max: Option[A])(implicit num: Numeric[A]) extends Serializable { | |
/** if max nonEmpty, then max > min */ | |
require(testRightBound(max, min)) | |
def in(value: A): Boolean = | |
value >= min && testRightBound(max, value) | |
def +(value: A): Interval[A] = | |
new Interval(num.plus(min, value), max.map(num.plus(_, value))) | |
private def testRightBound(max: Option[A], value: A): Boolean = | |
max.isEmpty || max.exists(_ > value) | |
private def canEqual(a: Any): Boolean = a.isInstanceOf[Interval[_]] | |
override def equals(that: Any): Boolean = | |
that match { | |
case that: Interval[_] => | |
that.canEqual(this) && | |
this.min == that.min && | |
this.max == that.max | |
case _ => false | |
} | |
override def hashCode(): Int = 13 * min.## + max.map(_.##).getOrElse(0) | |
override def toString: String = (List(min) ++ max.toList).mkString("Interval(", ",", ")") | |
} | |
object Interval { | |
def apply[A](min: A, max: A)(implicit num: Numeric[A]) = new Interval(min, Some(max)) | |
def apply[A](min: A)(implicit num: Numeric[A]) = new Interval(min, None) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment