Softwaredesign: Beispiel: Double Dispatch durch Mustervergleich in Haskell |
1module Zahl
2where
3
4data Zahl = Ganz Integer
5 | Rat Integer Integer
6 | Reell Double
7 deriving (Show)
8
9plus :: Zahl -> Zahl -> Zahl
10
11plus (Ganz i1) (Ganz i2) = Ganz (i1 + i2)
12plus (Ganz i1) (Rat z2 n2) = rat (i1 * n2 + z2) n2
13plus (Ganz i1) (Reell f2) = Reell (i2d i1 + f2)
14
15plus (Rat z1 n1) (Ganz i2) = rat (z1 + i2 * n1) n1
16plus (Rat z1 n1) (Rat z2 n2) = rat (z1 * n2 + z2 * n1) (n1 * n2)
17plus (Rat z1 n1) (Reell f2) = Reell (i2d z1 / i2d n1 + f2)
18
19plus (Reell f1) (Ganz i2) = Reell (f1 + i2d i2)
20plus (Reell f1) (Rat z2 n2) = Reell (f1 + i2d z2 / i2d n2)
21plus (Reell f1) (Reell f2) = Reell (f1 + f2)
22
23-- Problem: 3 Varianten von Zahlen,
24-- also fuer 2-stellige Operationen
25-- 9 (= 3 * 3) Fallunterscheidungen
26
27-- Konversion Integer -> Double
28
29i2d :: Integer -> Double
30i2d = fromInteger
31
32-- "intelligenter" Konstruktor fuer rationale Zahlen
33
34rat :: Integer -> Integer -> Zahl
35rat z n
36 | n1 == 1 = Ganz z1
37 | otherwise = Rat z1 n1
38 where
39 g = z `gcd` n
40 z1 = z `div` g
41 n1 = n `div` g
|
Letzte Änderung: 13.04.2012 | © Prof. Dr. Uwe Schmidt |