I have this:
data Vector3 t = Vector3 { ax, ay, az :: t }
data Point3 t = Point3 { x, y, z :: t }
data Ray3 t = Ray3 { ori :: Point3 t, dir :: Vector3 t }
data Sphere t = Sphere { center :: Point3 t, radius :: t }
I want a Shape type class, so I did this:
class Shape s where
distance :: s -> Ray3 t -> t
distance
takes a shape and a ray and computes the distance to the shape along the given ray. When I try to create an instance, it doesn't work. This is what I have so far:
instance Shape (Sphere t) where
distance (Sphere center radius) ray = -- some value of type t --
How do I create an instance of Shape? I've tried everything I can think of, and I'm getting all kind of errors.
The problem is that the type variable t
in Sphere t
is not the same as the one in the type signature of distance
. Your current types are saying that if I have a Sphere t1
, I can check it against a Ray3 t2
. However, you probably want these to be the same type. To solve this, I would change the Shape
class to
class Shape s where
distance :: s t -> Ray3 t -> t
Now the dependency on t
is explicit, so if you write your instance as
instance Shape Sphere where
distance (Sphere center radius) ray = ...
the types should line up nicely, although you'll probably need to add in some numeric constraints on t
to do any useful calculations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With