我有这个:
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 }
我想要一个 Shape 类型类,所以我这样做了:
class Shape s where
distance :: s -> Ray3 t -> t
distance
取一个形状和一条射线,并计算沿给定射线到该形状的距离。当我尝试创建一个实例时,它不起作用。这是我到目前为止:instance Shape (Sphere t) where
distance (Sphere center radius) ray = -- some value of type t --
如何创建 Shape 的实例?我已经尝试了所有我能想到的方法,但我遇到了各种错误。
最佳答案
问题是类型变量t
在 Sphere t
与distance
的类型签名中的不一样.您目前的类型是说,如果我有 Sphere t1
,我可以对照 Ray3 t2
来检查它.但是,您可能希望它们是相同的类型。为了解决这个问题,我将更改 Shape
上课到
class Shape s where
distance :: s t -> Ray3 t -> t
现在依赖于
t
是明确的,所以如果你把你的实例写成instance Shape Sphere where
distance (Sphere center radius) ray = ...
类型应该很好地排列,尽管您可能需要在
t
上添加一些数字约束做任何有用的计算。
关于haskell - 这个类/实例有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7670471/