这个类/实例有什么问题?

时间:2011-10-06 05:07:13

标签: haskell typeclass

我有这个:

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实例?我已经尝试了所有我能想到的东西,而且我遇到了各种各样的错误。

1 个答案:

答案 0 :(得分:9)

问题是t中的类型变量Sphere tdistance的类型签名中的类型变量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

类型应该很好地排列,尽管你可能需要在{{1}}上添加一些数字约束来进行任何有用的计算。

相关问题