Bool
|
Boolesche Werte |
|
|
| |
Operatoren
|
&&, ||, not
|
| |
Funktionsdefinition
|
verschiedene Varianten
|
| |
.1
|
and :: Bool -> Bool -> Bool
and x y = x && y
exOr :: Bool -> Bool -> Bool
exOr x y = (x || y) && not ( x && y )
|
| |
.2 Muster
|
and True y = y
and False y = False
exOr True y = not y
exOr False y = y
|
| |
.3 Wahrheitstabelle
|
and True True = True
and True False = False
and False True = False
and False False = False
exOr True True = False
exOr True False = True
exOr False True = True
exOr False False = False
|
| |
.4 if
|
and x y = if x then y else False
exOr x y = if x then not y else y
|
| |
.5 case
|
and x y =
case x of
True -> y
False -> False
exOr x y =
case x of
True -> not y
False -> y
|
| |
?
|
Sind .1 bis .5 äquivalent?
|
|
.3 ist strikt in beiden Argumenten,
.1, .2, .4 und .5 sind nur im ersten Argument strikt.
|
| |
|
Regelschreibweise "nur" syntaktischer Zucker
aber die Lesbarkeit wird verbessert
|
| |
|
"pattern matching", Mustervergleich ist noch
allgemeiner möglich.
|
| |
|
Mustervergleich in Funktionen
wird intern zurückgeführt auf case-Ausdrücke
|
| |
Gleichheitstest
|
(==) :: Bool -> Bool -> Bool
x == y = (x && y) || (not x && not y)
(/=) :: Bool -> Bool -> Bool
x /= y = not (x == y)
|
| |
|
== ist auch auf anderen Typen definiert, aber nicht auf allen.
|
|
/= ist eine allgemein gültige Definition
|
| |
Lösung
|
Typklassen
|
| |
Literatur
|
LYAH: Types and Typeclasses
|
| |
Eq
|
eine Typklasse für Gleichheitstest
|
|
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
|
| |
|
In Java oder C++: Eine Schnittstelle oder abstrakte Klasse
|
| |
Eq für Bool
|
instance Eq Bool where
x == y = (x && y) || (not x && not y)
x /= y = not (x == y)
|
| |
Eq
|
mit default-Definiton
|
|
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
x /= y = not (x == y)
|
| |
|
Bool braucht nur noch == zu definieren.
|
| |
Ord
|
eine Typklasse für eine totale Ordnung
|
| |
Voraussetzung
|
Es gibt einen Gleichheitstest
|
|
class Eq a => Ord a where
(<), (<=), (>=), (>) :: a -> a -> Bool
max, min :: a -> a -> a
compare :: a -> a -> Ordering
x <= y = (x < y) || (x == y)
x >= y = (x > y) || (x == y)
x > y = not (x <= y)
min x y = if x < y then x else y
max x y = if x > y then x else y
data Ordering = LT | EQ | GT
|
| |
|
Nur < muss für Bool definiert werden
|
| |
Ord für Bool
|
instance Ord Bool where
False < False = False
False < True = True
True < False = False
True < True = False
|
oder
|
instance Ord Bool where
False < True = True
_ < _ = False
|
| |