20-CS-4003-001 Organization of Programming Languages Fall 2017
Types

Lambda calculus, Type theory, Formal semantics, Program analysis

Prev     Next     All lectures           Code

Type Classes

data Color = Red | Green | Yellow | Blue | Indigo

data Maybe a = Nothing | Just a deriving (Show)

instance Eq Color where
  Red == Red = True
  Green == Red = True
  Green == Green = True
  Yellow == Yellow = True
  Blue == Blue = True
  Indigo == Indigo = True
  _ == _ = False

instance Show Color where
  show Red = "showing Red"
  show Green = "showing Green"
  show _ = "cannot show color"

instance Eq (m) => Eq (Main.Maybe m) where
  Main.Just x == Main.Just y = x == y
  Main.Nothing == Main.Nothing = True
  _ == _ = False
  
class YesNo a 
  where  
    yesno :: a -> Bool  
		
instance YesNo Integer where
  yesno 0 = False  
  yesno _ = True  
			 
instance YesNo [a] where  
  yesno [] = False  
  yesno _ = True 
  -   Type classes can be defined and instances generated. Equality of Color is defined to the left
 *Main> Red == Green
 False
 *Main> Green == Red
 True
Showing a Color is also redefined.
 *Main> Red
 showing Red
 *Main> Yellow
 cannot show color
Eq for Maybe requires adding the type variable m so what's contained inside the Maybe is also a member of the Eq class. Otherwise, x == y does not work (Haskell is not sure x or y have Eq definition).