Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 232
usr Avatar asked Feb 05 '26 19:02

usr


2 Answers

{-# 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
like image 85
ephemient Avatar answered Feb 09 '26 02:02

ephemient


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.

like image 29
Nathan Shively-Sanders Avatar answered Feb 09 '26 00:02

Nathan Shively-Sanders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!