Search code examples
haskelltypestypeclassexistential-typegadt

Haskell question: constraining data types to use show


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?


Solution

  • {-# 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