Code:
data Exp a = Const a | Eq (Exp a) (Exp a)
I want the Const a to contain a value of type show so that i can print it later. So in C# i would write:
class Const : Exp { IShow X; }
class Eq : Exp { Exp X, Y; }
How can i do that in Haskell?
{-# LANGUAGE GADTs #-}
data Exp a where
Const :: Show a => a -> Exp a
Eq :: Exp a -> Exp a -> Exp a
If you want to allow for varying data types in different branches of Eq that's fine too.
data Exp where
Const :: Show a => a -> Exp
Eq :: Exp -> Exp -> Exp
You can do this by saying
data (Show a) => Exp a = Const a | Eq (Exp a) (Exp a)
But this is almost always a bad idea because it forces every function that uses Exp to mention the show constraint, even if it never uses the Show methods. Instead, put the show constraint on just the functions it's relevant for. See Real World Haskell for an explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With