How to do implicit type conversion used in my interpreter

I am writing an interpreter and trying to use the solution from how-to-set-up-implicit-conversion-to-allow-arithmetic-between-numeric-types for the same problem, I should be able to add Boolean + Boolean, Int + Boolean, Boolean + Int, Int + Double, Double + Double, etc.

So I used WeakConformance and C classes from this solution

sealed trait WeakConformance[A <: AnyVal, B <: AnyVal, C] {
  implicit def aToC(a: A): C

  implicit def bToC(b: B): C
}

object WeakConformance {
  implicit def SameSame[T <: AnyVal]: WeakConformance[T, T, T] = new WeakConformance[T, T, T] {
    implicit def aToC(a: T): T = a

    implicit def bToC(b: T): T = b
  }

  implicit def IntDouble: WeakConformance[Int, Double, Double] = new WeakConformance[Int, Double, Double] {
    implicit def aToC(a: Int) = a

    implicit def bToC(b: Double) = b
  }

  implicit def DoubleInt: WeakConformance[Double, Int, Double] = new WeakConformance[Double, Int, Double] {
    implicit def aToC(a: Double) = a

        implicit def bToC(b: Int) = b
      }
   }  

   case class C[A <: AnyVal](val value:A) {
          import WeakConformance.unify
          def +[B <: AnyVal, WeakLub <: AnyVal](that:C[B])(implicit wc: WeakConformance[A, B, WeakLub], num: Numeric[WeakLub]): C[WeakLub] = {  
        new C[WeakLub](num.plus(wc.aToC(x), wc.bToC(y)))
      }
    }

and here is part of my interpreter

class Interpreter {

......

  def eval(e: Expression): Any = e match {
  ...

    case ADD(lhs, rhs) => (eval(lhs), eval(rhs)) match {

      case (l: C[_], r: C[_]) => l + r  // error comes here

      case _ => error("...")
    }
  }

}

the error is similar to the error

error: ambiguous implicit values: // indicates that the last 2 objects declared as implicit in Numericcorrespond here to the expected typeNumeric[WeakLub]

, ? , eval C, C[Int] C[Any],

+3
1

- C. . . , .

+1

Source: https://habr.com/ru/post/1751409/


All Articles