我想为双精度数组定义一些隐式方法,以使我的代码更简洁。理想情况下,它们看起来像这样:
type Vec = Array[Double]
implicit def enrichVec(v: Vec) = new {
def /(x: Double) = v map (_/x)
def *(u: Vec) = (v zip u) map {case (x,y) => x*y} sum
def normalize = v / math.sqrt(v * v)
}
然而,该normalize
函数不能像编写的那样工作,因为 Scala 不会递归地应用隐式方法。具体来说,我得到一个错误Note: implicit method enrichVec is not applicable here because it comes after the application point and it lacks an explicit result type
。我可以通过显式写出 的代码来避免这种情况normalize
,但这会很丑陋。有更好的解决方案吗?