Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining an instance to a restricted a type in Haskell

Tags:

haskell

I am working with the following Data Type:

data Exp a =
|Const a
|Simetrico (Exp a)
|Mais (Exp a) (Exp a)
|Menos (Exp a) (Exp a)
|Mult (Exp a) (Exp a)

but a is supposed to be a Numeric type. I would define Eq like this:

instance Eq (Exp a) where
         a == b | ... = True
                | otherwise = False

but I am saying nowhere that my a is a numeric type, so ghci complains, how do I solve this ?

like image 361
DeltaX Gamer PT Avatar asked Dec 07 '25 06:12

DeltaX Gamer PT


1 Answers

You add a type constraint to the instance clause:

instance Num a => Eq (Exp a) where
         a == b | ... = True
                | otherwise = False

So now you can assume (in the scope of the instance) that a is an instance of the Num typeclass.

like image 94
Willem Van Onsem Avatar answered Dec 10 '25 01:12

Willem Van Onsem