[Haskell-cafe] Parsing different types, same typeclass

José Lopes jose.lopes at ist.utl.pt
Sat Nov 17 15:59:59 CET 2012

Hello everyone,

I was wondering if you could help me!

So, I have a typeclass "Action" which defines method "run":

class Action a where
     run :: a -> Int

and two data types that are instances of this typeclass:

data A = A Int
         deriving (Read, Show)

instance Action A where
     run (A n) = n

data B = B Int
         deriving (Read, Show)

instance Action B where
     run (B n) = n

Now, I want to parse either "A" or "B" from a String.
I was thinking about something like this...

parseAction :: (Action a, Read a) => String -> a
parseAction str
     | "(A " `isPrefixOf` str = (read :: String -> A) str
     | "(B " `isPrefixOf` str = (read :: String -> B) str

The problem is that when calling "parseAction" I get "ambiguous type
constraints". How to implement a parse function for two distinct
types that share the same typeclass "Action". Because after calling
"parseAction" I don't whether "A" or "B" was returned: I only care
that they are "Action" instances so I can call "run".

Best regards,

More information about the Haskell-Cafe mailing list