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

标签 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 的实例?我已经尝试了所有我能想到的方法,但我遇到了各种错误。

最佳答案

问题是类型变量tSphere 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 上添加一些数字约束做任何有用的计算。

关于haskell - 这个类/实例有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7670471/

相关文章:

haskell - 检查函数中的 Haskell 类型类

haskell - 为什么不能将 Int 与 Nums 或 Ords 进行比较?

haskell - 修改成员变量的惯用方法

haskell - list-to-tree 函数的渐近运行时

haskell - 根据类别选择功能

typeclass - 在类型类中使用类型类实例

haskell - Haskell 中的函数类型推断

haskell - 计数/获取分层数据的 "Level"

haskell - 观察类型理论中的模式匹配

haskell - 存在类型类 vs. 数据构造函数 vs. 副产品