next up previous contents
Next: Übungen Up: Benutzerdefinierte Datentypen und Typklassen Previous: Abstrakte Datentypen

Klassen

sind in Haskell Typklassen, dh Kollektionen von Typen, die durch einen gemeinsamen Satz von Operationen ausgezeichnet sind.

Idee aus der OO-Welt, aber in Haskell:

Beispiel: benutzerdefinierter Datentyp als Instanz von Eq:

 -------------------old defs do not support "=":


data PrimaryColour = Yellow | Red | Blue


--------------------------as is shown by:
{-
Main> Yellow == Blue


ERROR: PrimaryColour is not an instance of class "Eq"
-}


-------------so make new type an instance of class Eq:


data PrimaryColour = Yellow | Red | Blue
instance Eq PrimaryColour
where Yellow == Yellow = True
Red == Red = True
Blue == Blue = True
_ == _ = True


---------------------------which allows:
{-
Main> Yellow == Blue
False
-}


-------------------this can be done more simply:


data PrimaryColour = Yellow | Red | Blue deriving Eq


-----------------------which gives the same:
{-
Main> Yellow == Blue
False
Main> Yellow /= Blue
True
-}


-----but other defs of "==" could be useful for colour blinds:


data PrimaryColour = Yellow | Red | Blue
instance Eq PrimaryColour
where _ == _ = True


------------------------------giving:
{-
Main> Yellow == Blue
True
-}

Beispiel: Definition einer Klasse und zweier Instanzen

 -------------------now define your own classes:


class Mail m
where giveAdr:: m->String
setAdr:: String->m->m
existsAdr:: m->Bool
existsAdr x = (giveAdr x /= "") - default


data SimpleLetter a = SL String a - hat eine Adresse
instance Mail (SimpleLetter a)
where giveAdr (SL s _) = s
setAdr s (SL s' x) = (SL s x)


data BroadcastLetter a = BC [String] a - hat Liste von Adressen
clearAdr:: (BroadcastLetter a)->(BroadcastLetter a)
clearAdr (BC ss x) = BC [] x


instance Mail (BroadcastLetter a)
where giveAdr (BC [] _) = ""
giveAdr (BC (s:ss) _) = s
setAdr s (BC ss x) = BC (s:ss) x


-----------------------------examples:
{-
Main> existsAdr (SL "Grete" (25, "Now", 1997))
True
Main> giveAdr(setAdr "Gustav" (setAdr "Franz"
(SL "Grete" (25, "Nov", 1997))))
"Gustav"
Main> giveAdr (clearAdr (BC ["Grete"] (25, "Nov", 1997)))
""
Main> existsAdr (clearAdr (BC ["Grete"] (25, "Nov", 1997)))
False
-}


next up previous contents
Next: Übungen Up: Benutzerdefinierte Datentypen und Typklassen Previous: Abstrakte Datentypen
Ronald Blaschke
1998-04-19