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
tinSphere tis not the same as the one in the type signature ofdistance. Your current types are saying that if I have aSphere t1, I can check it against aRay3 t2. However, you probably want these to be the same type. To solve this, I would change theShapeclass toNow the dependency on
tis explicit, so if you write your instance asthe types should line up nicely, although you’ll probably need to add in some numeric constraints on
tto do any useful calculations.