Recursively using implicit methods in Scala

I'd like to define some implicit methods for arrays of doubles to make my code cleaner. Ideally, they would look like this:

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

However the normalize function doesn't work as written because Scala won't apply implicit methods recursively. Specifically, I get an error Note: implicit method enrichVec is not applicable here because it comes after the application point and it lacks an explicit result type. I could avoid this by explicitly writing out the code for normalize, but that would be ugly. Is there a nicer solution?

Answers


The anonymous class inhibits the recursive function definitions. You need to define the "RichVec" as a class and then separately define the implicit conversion.

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

Need Your Help

develop ios 8 keyboard and widgets using flash air

flash air keyboard ios8 ios-app-extension

IOS 8 will have third-party keyboard and widgets as apple said

Can i add website analytics to my custom CMS

php html website statistics analytics

I have built my own Content Management system for my sites, I want to add some "Website stats" (visitors etc) to it.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.