3
votes

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

So I used WeakConformance and C classes from that 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 like that

error: ambiguous implicit values: // shows 2 last objects declared as implicit in Numeric trait here match expected type Numeric[WeakLub]

any ideas how to make it work? I wanted to make the eval method to return C but since C[Int] is not an instance of C[Any] it doesn't solve my problem

1

1 Answers

1
votes

Because of type erasure, you can't retrieve at run-time the type parameter of C. You'll need to use manifests to store that information. See questions related to manifest and type erasure.