Aufzählungen

  • Der einfachste Aufzählungstyp (standard prelude):
data Bool = False | True  
  • Typbezeichner und Werte beginnen mit Großbuchstaben
  • Bool hat genau zwei mögliche Werte
  • True und False sind die Konstruktoren des Typs Bool
  • Konstruktoren müssen einmalig sein

Verwendung neuer Datentypen

data CardDir = North | South | East | West  

Verwendung von CardDir

Datentypen mit Parametern

data Date = Datum Year Month Day  
type Year = Int  
data Month = Jan | Feb | Mar | ...  
type Day = Int  

Was ist bei Date der Konstruktor? – Datum, eine dreistellige Funktion:

> :t Datum   
Datum :: Year -> Month -> Day -> Date  

Verwendung von Date Selektor

day :: Date -> Day   
day (Datum y m d) = d   
  
month :: Date -> Month   
month (Datum y m d) = m  

Warum “Algebraische” Datentypen?

Algebraische Datentypen verallgemeinert

  • Kartesische Produkte UND Disjunktion von Werten und
  • Rekursive Algebraische Datenstrukturen
data Shape = Circle Float | Rect Float Float   
  
square :: Float -> Shape   
square a = Rect a a  
  
area :: Shape -> Float   
area (Circle r) = pi * r^2   
area (Rect x y) = x * y  

Haskell Maybe

data Maybe a = Nothing | Just a  

vordefinierte Funktionen

import Data.Maybe  
  
fromJust :: Maybe a -> a   
  
> fromJust (Just 42)  
42   
  
-- es gibt auch  
maybeToList :: Maybe a -> [a]  
  
--   
aber:  
> maybeToList Nothing []  
[]  
> maybe "Fehler" (show) 42  
"42"  
  
> maybe "Fehler" (show) Nothing  
"Fehler"  
Link to original

Rekursive Algebraische Datentypen