Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- trait MyNumeric[T] {
- }
- trait MyIntNumeric[T] extends MyNumeric[T]{
- def sub(x: T, y: T): T
- def div(x: T, y: T): T
- def mul(x: T, y: T): T
- }
- object MyIntNumeric {
- implicit object IntIsMyNumeric extends MyIntNumeric[Int] {
- def sub(x: Int, y: Int) = x - y
- def div(x: Int, y: Int) = x / y
- def mul(x: Int, y: Int) = x * y
- }
- implicit object LongIsMyNumeric extends MyIntNumeric[Long] {
- def sub(x: Long, y: Long) = x - y
- def div(x: Long, y: Long) = x / y
- def mul(x: Long, y: Long) = x * y
- }
- }
- trait MyFloatNumeric[T] extends MyNumeric[T]{
- def sub(x: T, y: T): T
- def div(x: T, y: T): T
- def mul(x: T, y: T): T
- }
- object MyNumeric {
- implicit object FloatIsMyNumeric extends MyFloatNumeric[Float] {
- def sub(x: Float, y: Float) = x - y
- def div(x: Float, y: Float) = x / y
- def mul(x: Float, y: Float) = x * y
- }
- implicit object DoubleIsMyNumeric extends MyFloatNumeric[Double] {
- def sub(x: Double, y: Double) = x - y
- def div(x: Double, y: Double) = x / y
- def mul(x: Double, y: Double) = x * y
- }
- }
- class Fraction[T] (n: T, d: T)(implicit num: MyIntNumeric[T]) {
- val numerator : T = num.div(n, gcd(n, d))
- val denominator : T = num.div(d, gcd(n, d))
- def gcd (x: T, y: T): T =
- if (0 == y) x else gcd(y, num.sub(x, num.mul(y, num.div(x, y))))
- override def toString = {
- if (0 == numerator) "{0}"
- else if (1 == denominator) "{" + numerator + "}"
- else if (numerator == denominator) "{1}"
- else "{" + numerator + "}/{" + denominator + "}"
- }
- }
- class EquationSystem[T] (a: T, b: T, c: T, d: T, e: T, f: T)(implicit num: MyNumeric[T]) {
- //x = (c*e-a*b) / (a*e - b*d)
- //a*f - c*d / a*e - b*d
- //num.div(num.sub(num.times(c,e), num.times(a,b)),
- //num.sub(num.times(a,e), num.times(b,d)))
- def solve[T]()(implicit num: MyIntNumeric[T]): (Fraction[T], Fraction[T]) = {
- (new Fraction[T](
- num.sub(num.mul(c, e), num.mul(a, b)),
- num.sub(num.mul(a, e), num.mul(b, d))),
- new Fraction[T](
- num.sub(num.mul(c, e), num.mul(a, b)),
- num.sub(num.mul(a, e), num.mul(b, d))))
- }
- def solve[T]()(implicit num: MyFloatNumeric[T]): (T, T) = {
- (num.div(
- num.sub(num.mul(c, e), num.mul(a, b)),
- num.sub(num.mul(a, e), num.mul(b, d))),
- num.div(
- num.sub(num.mul(c, e), num.mul(a, b)),
- num.sub(num.mul(a, e), num.mul(b, d)))
- )
- }
- override def toString = "\n" +
- a + "*X + " + b + "*Y = " + c + "\n" +
- d + "*X + " + e + "*Y = " + f
- }
- object Main {
- def main(args: Array[String]): Unit = {
- val e = new Fraction[Int](26, 74)
- println(e)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment