« Return to Thread: [scala] vector math parameterized class in scala

Re: [scala] vector math parameterized class in scala

by Landei :: Rate this Message:

Reply to Author | View in Thread


Jonathan Bachrach-2 wrote:
i'm trying to define a vector math class using parameterized classes  
in scala and am having trouble.  here's an abbreviated version of what  
i wrote:

class Vec3[T <: Number] (xa: T, ya: T, za: T) {
   val x: T = xa; val y: T = ya; val z: T = za
   def + (o: Vec3[T]): Vec3[T] = new Vec3(x + o.x, y + o.y, z + o.z)
   def * (s: T): Vec3[T] = new Vec3(x * s, y * s, z * s)
   def len (): T = x + y + z
   def == (o: Vec3[T]): Boolean = x == o.x && y == o.y && z == o.z
   def < (o: Vec3[T]): Boolean = x < o.x && y < o.y && z < o.z
}

and here's what scalac says:

rala-692> scalac vec3.scala
vec3.scala:3: error: type mismatch;
  found   : T
  required: String
   def + (o: Vec3[T]): Vec3[T] = new Vec3(x + o.x, y + o.y, z + o.z)
                                                ^
vec3.scala:3: error: type mismatch;
  found   : T
  required: String
   def + (o: Vec3[T]): Vec3[T] = new Vec3(x + o.x, y + o.y, z + o.z)
                                                         ^
vec3.scala:3: error: type mismatch;
  found   : T
  required: String
   def + (o: Vec3[T]): Vec3[T] = new Vec3(x + o.x, y + o.y, z + o.z)
                                                                  ^
vec3.scala:4: error: value * is not a member of T
   def * (s: T): Vec3[T] = new Vec3(x * s, y * s, z * s)
                                      ^
vec3.scala:4: error: value * is not a member of T
   def * (s: T): Vec3[T] = new Vec3(x * s, y * s, z * s)
                                             ^
vec3.scala:4: error: value * is not a member of T
   def * (s: T): Vec3[T] = new Vec3(x * s, y * s, z * s)
                                                    ^
vec3.scala:5: error: type mismatch;
  found   : T
  required: String
   def len (): T = x + y + z
                       ^
vec3.scala:7: error: value < is not a member of T
   def < (o: Vec3[T]): Boolean = x < o.x && y < o.y && z < o.z
                                   ^
8 errors found

i had added the T <: Number to try to make it so that the + would be  
compatible but it still thinks + only works with strings.  i'm not  
even completely sure that Number is a real Scala Class.  i'm obviously  
not understanding how to write parameterized classes in scala.  any  
help would be appreciated.
Hi!

There is a blog series about matrices, which uses a cute trick for abstracting over numeric types:

http://dcsobral.blogspot.com/2009/07/matrices-6.html

Cheers,
Daniel

 « Return to Thread: [scala] vector math parameterized class in scala