I want to write a function that works for all my custom datatypes (that are part of my custom typeclass), but each datatype has their own implementation. For example:
getValue :: Ent entity => entity -> Float
getValue (Player position _) = doA position
getValue (Enemy position) = doB position
This however gives me the following error:
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
How can I write a function that has a unique implementation for all the types of my typeclass?
CodePudding user response:
You do this in the type class, making getValue
its method:
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
Now getValue :: Ent a => a -> Float
which is the same thing as you wanted.
Type variables' names don't count, up to consistent renaming.