4

我想为双精度数组定义一些隐式方法,以使我的代码更简洁。理想情况下,它们看起来像这样:

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,但这会很丑陋。有更好的解决方案吗?

4

2 回答 2

6

匿名类禁止递归函数定义。您需要将“RichVec”定义为一个类,然后单独定义隐式转换。

type Vec = Array[Double]
implicit def enrichVec(v: Vec) = RichVec( v )
case class RichVec( v: Vec ) {
  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 )
}
于 2011-11-30T03:54:03.653 回答
0

这有效:

type Vec = Array[Double]
abstract class RichVec(v: Vec) {
  def /(x: Double): Vec
  def *(u: Vec): Double
  def normalize: Vec
}
implicit def enrichVec(v: Vec): RichVec = new RichVec( v ) {
  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)
}

但是还有其他方法可以做到这一点。最重要的是为隐式指​​定返回类型

于 2011-11-30T16:12:38.120 回答