gpt4 book ai didi

scala - 如何对我的解释器中使用的类型进行隐式转换

转载 作者:行者123 更新时间:2023-12-04 17:56:34 26 4
gpt4 key购买 nike

我正在编写解释器并尝试使用 how-to-set-up-implicit-conversion-to-allow-arithmetic-between-numeric-types 中的解决方案对于同样的问题,我需要能够添加 Boolean + Boolean、Int + Boolean、Boolean + Int、Int + Double、Double + Double 等。

所以我使用了该解决方案中的 WeakConformance 和 C 类

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)))
}
}

这是我的翻译的一部分
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("...")
}
}

}

错误是这样的

错误:不明确的隐含值://显示在 Numeric 中声明为隐含的最后 2 个对象此处的特征匹配预期类型 Numeric[WeakLub]
任何想法如何使它工作?我想让 eval 方法返回 C但自从 C[Int]不是 C[Any] 的实例它不能解决我的问题

最佳答案

由于类型删除,您无法在运行时检索 C 的类型参数.您需要使用 list 来存储该信息。请参阅与 list 和类型删除相关的问题。

关于scala - 如何对我的解释器中使用的类型进行隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3102666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com