如何对类型类约束参数进行类型转换?

How do I typecast over a typeclass constrainted parameter?

我想编写一个适用于我所有自定义数据类型(属于我的自定义类型类的一部分)的函数,但每个数据类型都有自己的实现。例如:

getValue :: Ent entity => entity -> Float
getValue (Player position _) = doA position
getValue (Enemy position) = doB position

然而,这给了我以下错误:

Couldn't match expected type ‘entity’ with actual type ‘Player’  
‘entity’ is a rigid type variable bound by  
  the type signature for:  
   getValue :: forall entity. Ent entity => entity -> Float

我如何编写一个函数,它对我的​​类型类的所有类型都有唯一的实现?

你在 类型 class 中执行此操作,使 getValue 成为其 方法 :

class Ent a where
   getValue :: a -> Float

instance Ent Player where
   getValue (Player p _) = doA p

instance Ent Enemy where
   getValue (Enemy e) = doB e

现在getValue :: Ent a => a -> Float这就是你想要的。

类型变量的名称不算数,直至一致重命名。