Softwaredesign: Beispiel: Arithmetische Ausdrücke als Kompositum |
1-- simple data model for arithmetic expressions
2
3module ArithmeticExpression
4where
5
6data Expr
7 = Const Value
8 | UnExpr UnOp Expr
9 | BinExpr BinOp Expr Expr
10 deriving (Eq, Show)
11
12data Value
13 = I Int
14 | D Double
15 deriving (Eq, Show)
16
17data UnOp
18 = UnPlus
19 | UnMinus
20 | IntToDouble
21 | DoubleToInt
22 deriving (Eq, Show)
23
24data BinOp
25 = Plus
26 | Minus
27 | Mult
28 deriving (Eq, Show)
29
30-- ------------------------------------------------------------
31--
32-- an evaluator
33
34eval :: Expr -> Value
35
36eval (Const v) = v
37eval (UnExpr op e1) = eval1 op (eval e1)
38eval (BinExpr op e1 e2) = eval2 op (eval e1) (eval e2)
39
40eval1 :: UnOp -> Value -> Value
41
42eval1 UnPlus v = v
43eval1 UnMinus (I i) = I (0 - i)
44eval1 UnMinus (D d) = D (0.0 - d)
45eval1 IntToDouble (I i) = D (fromInteger (toEnum i))
46eval1 DoubleToInt (D d) = I (fromEnum (round d))
47eval1 _ _ = error "illegal unary operation"
48
49eval2 :: BinOp -> Value -> Value -> Value
50
51eval2 Plus (I i1) (I i2) = I (i1 + i2)
52eval2 Plus (D d1) (D d2) = D (d1 + d2)
53eval2 Minus (I i1) (I i2) = I (i1 - i2)
54eval2 Minus (D d1) (D d2) = D (d1 - d2)
55eval2 Mult (I i1) (I i2) = I (i1 * i2)
56eval2 Mult (D d1) (D d2) = D (d1 * d2)
57eval2 _ _ _ = error "illegal binary operation"
58
59-- ------------------------------------------------------------
60--
61-- some example expressions
62
63e0 = Const (I 3)
64
65e1 = BinExpr Plus
66 (Const (I 48))
67 (UnExpr UnMinus (BinExpr Plus e0 e0))
68
69e2 = BinExpr Minus
70 (BinExpr Mult (Const (I 15)) e0)
71 e0
72
73v0 = eval e0
74v1 = eval e1
75v2 = eval e2
|
Letzte Änderung: 27.05.2014 | © Prof. Dr. Uwe Schmidt |