Home > Back-end >  How do I typecast over a typeclass constrainted parameter?
How do I typecast over a typeclass constrainted parameter?

Time:11-05

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 typePlayer
‘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.

  • Related