在Scala中递归使用隐式方法

dav*_*dsd 4 scala implicit implicit-methods

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

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)
}
Run Code Online (Sandbox Code Playgroud)

但是,该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,但那会很难看.有更好的解决方案吗?

Nei*_*ssy 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 )
}
Run Code Online (Sandbox Code Playgroud)