我有这个:
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 }
Run Code Online (Sandbox Code Playgroud)
我想要一个Shape类型,所以我这样做了:
class Shape s where
distance :: s -> Ray3 t -> t
Run Code Online (Sandbox Code Playgroud)
distance获取形状和光线并计算沿给定光线到形状的距离.当我尝试创建一个实例时,它不起作用.这是我到目前为止:
instance Shape (Sphere t) where
distance (Sphere center radius) ray = -- some value of type t --
Run Code Online (Sandbox Code Playgroud)
如何创建Shape实例?我已经尝试了所有我能想到的东西,而且我遇到了各种各样的错误.
问题是,该类型的变量t中Sphere t是不一样的所述一个中的类型签名distance.你当前的类型是说,如果我有Sphere t1,我可以检查它Ray3 t2.但是,您可能希望这些类型相同.要解决这个问题,我会将Shape课程更改为
class Shape s where
distance :: s t -> Ray3 t -> t
Run Code Online (Sandbox Code Playgroud)
现在依赖t是显式的,所以如果你把你的实例写成
instance Shape Sphere where
distance (Sphere center radius) ray = ...
Run Code Online (Sandbox Code Playgroud)
虽然你可能需要添加一些数字约束t来进行任何有用的计算,但这些类型应该很好地排列.