我正在尝试设计玩具CoversionRate
实现,以了解如何通过链接的隐式定义对“法律”进行编码。以下代码编译:
case class ConversionRate[X <: Currency, Y <: Currency](rate: Double) extends AnyVal
object ConversionRate {
implicit val EUR2USD: ConversionRate[EUR.type, USD.type] = ConversionRate(1.1)
implicit val GBP2USD: ConversionRate[GBP.type, USD.type] = ConversionRate(1.21)
// "Laws"
implicit def inverse[X <: Currency, Y <: Currency](implicit cr: ConversionRate[X, Y]): ConversionRate[Y, X] =
ConversionRate[Y, X](1 / cr.rate)
implicit def transitivity[X <: Currency, Z <: Currency](implicit cr: ConversionRate[X, USD.type], cr2: ConversionRate[Z, USD.type]): ConversionRate[X, Z] =
ConversionRate(cr.rate * cr2.rate)
private val unit = ConversionRate(1)
implicit def self[X <: Currency]: ConversionRate[X,X] = unit.asInstanceOf
}
然而,呼叫站点派生确实有效[>]val cr = implicitly[ConversionRate[EUR.type, GBP.type]]
diverging implicit expansion for type ConversionRate[EUR.type,GBP.type]
starting with method transitivity in object ConversionRate
我应该如何以可以用于推导的方式编写法律?
我正在尝试设计一个玩具CoversionRate实现,以了解如何通过链接的隐式定义对“法则”进行编码。编译以下代码:case类ConversionRate [X
id[X]: X => X
x: A => B
y: B => C