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

2

8

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

Schoolbook answered 8/7, 2010 at 7:48 Comment(3)
scala-notes.org/2010/06/… might help hereHiatus
@Hiatus thanks... that's my own blog! ;-)Schoolbook
"© 2010 Jesper de Jong"... riiiight. Well, sorry about that ;)Hiatus
R
9

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
}
Retail answered 11/7, 2010 at 12:51 Comment(5)
Interesting approach, but it produces a compiler error: gist.github.com/471620Schoolbook
Sorry - I don't have access to a working REPL at the moment. The approach will work, probably just a few rough edges to sort out!Retail
Looks like the problem has to do with the two terms a * (1.0 - t) and b * t both producing an X and then you're doing X + X instead of Interpolable[X] + Interpolable[X], the implicit isn't called for the + for some reason.Schoolbook
Ah, probably because the compiler decides to use Int + Int directlyRetail
Added view bound to X which has fixed the problemRetail
O
3

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

Oleum answered 8/7, 2010 at 13:4 Comment(2)
Really? That surprises me, Scala has such a powerful type system, yet this isn't possible. Thanks.Schoolbook
@Schoolbook I think I have read there's a type divergence problem related to supporting that.Oleum

© 2022 - 2024 — McMap. All rights reserved.