boost::intervalを羨むScala使い(Scalaで簡易版を実装してみた)
boost::intervalとはなんぞや
https://sites.google.com/site/boostjp/tips/interval_arithmetic
にあったりするが、要するに数値の範囲を扱うライブラリで、区間演算とかできたりするが、とりあえず範囲の重複だけでも取得したい!
と思ってScalaでその部分だけ実装してみたという話。
Scala Interval
case class Interval[T] (val from: T, val to: T)(implicit num: Numeric[T]) { import num.{mkNumericOps, mkOrderingOps} def mid: Double = (from.toDouble + to.toDouble)/2.0 def or(other: Interval[T]) = new Interval(from min other.from, to max other.to) def and(other: Interval[T]) = new Interval(from max other.from, to min other.to) def equals(right: Interval[T]) = from == right.from && to == right.to }
どっかからコピペしたものに付け足したから、余計なものとか入ってるけど気にしない。今回はテストもとりあえず書いたよ!
import org.scalatest.Suite class IntervalSuite extends Suite { def testEquals { assert(Interval(1, 2) == Interval(1, 2)) assert(Interval(1, 2) == Interval(1.0, 2.0)) } def testOr { expect( Interval(1, 6) ) { Interval(1, 5) or Interval(2, 6) } expect( Interval(1, 5) ) { Interval(1, 5) or Interval(2, 4) } expect( Interval(1.1, 6.1) ) { Interval(1.1, 5.1) or Interval(2.1, 6.1) } } def testAnd { expect( Interval(2, 5) ) { Interval(1, 5) and Interval(2, 6) } expect( Interval(2, 4) ) { Interval(1, 5) and Interval(2, 4) } expect( Interval(2.1, 5.1) ) { Interval(1.1, 5.1) and Interval(2.1, 6.1) } } }
なんというか適当であるな。