Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - how to define a structural type that refers to itself?

I'm trying to write a generic interpolate method that works on any type that has two methods, a * and a +, like this:

trait Container {
  type V = {
    def *(t: Double): V
    def +(v: V): V
  }

  def interpolate(t: Double, a: V, b: V): V = a * (1.0 - t) + b * t
}

This doesn't work though (on Scala 2.8.0.RC7), I get the following error messages:

<console>:8: error: recursive method + needs result type
           def +(v: V): V
                        ^
<console>:7: error: recursive method * needs result type
           def *(t: Double): V
                             ^

How do I specify the structural type correctly? (Or is there a better way to do this?)

like image 864
Jesper Avatar asked Jul 08 '10 07:07

Jesper


2 Answers

Surely you could solve this problem using the typeclasses approach (of e.g. Scalaz):

trait Multipliable[X] {
  def *(d : Double) : X
}

trait Addable[X] {
    def +(x : X) : X
}

trait Interpolable[X] extends Multipliable[X] with Addable[X]

def interpolate[X <% Interpolable[X]](t : Double, a : X, b : X)
    = a * (1.0 - t) + b * t

Then obviously you would need a (implicit) typeclass conversion in scope for all the types you cared about:

implicit def int2interpolable(i : Int) = new Interpolable[Int] {
  def *(t : Double) = (i * t).toInt
  def +(j : Int) = i + j
}

Then this can be run easily:

def main(args: Array[String]) {
  import Interpolable._
  val i = 2
  val j : Int = interpolate(i, 4, 5)

  println(j) //prints 6
}
like image 51
oxbow_lakes Avatar answered Oct 13 '22 20:10

oxbow_lakes


AFAIK, this is not possible. This was one of my own first questions.

like image 29
Daniel C. Sobral Avatar answered Oct 13 '22 21:10

Daniel C. Sobral