changeset 20:6d43207984ec

week 8 tutorial
author Markus Kaiser <markus.kaiser@in.tum.de>
date Wed, 12 Dec 2012 20:10:02 +0100
parents 6688bf4a5836
children 3fea6fff7265
files exercises/src/Exercise_8.hs
diffstat 1 files changed, 39 insertions(+), 13 deletions(-) [+]
line wrap: on
line diff
--- a/exercises/src/Exercise_8.hs	Fri Dec 07 01:34:16 2012 +0100
+++ b/exercises/src/Exercise_8.hs	Wed Dec 12 20:10:02 2012 +0100
@@ -6,15 +6,26 @@
 {---------------------------------------------------------------------}
 {- Aufgabe G8.1 -}
 
-f0 :: Fraction
-f0 = Over 1 2
-
-f1 :: Fraction
-f1 = Over 7 5
+data Fraction = Over Integer Integer deriving Show
 
 
 norm :: Fraction -> Fraction
-norm = undefined 
+norm (Over a b) = (a `div` c) `Over` (b `div` c)
+  where c = gcd a b * (if b < 0 then -1 else 1)
+
+instance Num Fraction where
+    (a1 `Over` b1) + (a2 `Over` b2) = norm $ (a1*b2 + a2*b1) `Over` (b1 * b2)
+    (a1 `Over` b1) * (a2 `Over` b2) = norm $ (a1 * a2) `Over` (b1 * b2)
+    abs (a `Over` b) = abs a `Over` abs b
+    signum (a `Over` b) = (signum a * signum b) `Over` 1
+    fromInteger n = n `Over` 1
+
+instance Eq Fraction where
+    (a1 `Over` b1) == (a2 `Over` b2) = a1*b2 == a2*b1
+
+instance Fractional Fraction where
+    recip (a `Over` b) = (b `Over` a)
+    fromRational r = numerator r `Over` denominator r
 
 
 
@@ -22,11 +33,11 @@
 {- Aufgabe G8.2 -}
 -- siehe Exercise_8_Form.hs
 
-p0 :: Form
-p0 = (Var "a" :&: Var "b") :|: (Not (Var "a") :&: Not (Var "b"))
+--p0 :: Form
+--p0 = (Var "a" :&: Var "b") :|: (Not (Var "a") :&: Not (Var "b"))
 
-p1 :: Form
-p1 = ((Not $ Not $ Var "a") :|: (Not ((Var "b") :->: (Not (Var "c")))))
+--p1 :: Form
+--p1 = ((Not $ Not $ Var "a") :|: (Not ((Var "b") :->: (Not (Var "c")))))
 
 
 
@@ -42,7 +53,11 @@
 
 
 evalArith :: [(String,Integer)] -> Arith -> Integer
-evalArith = undefined
+evalArith val (Add x y) = evalArith val x + evalArith val y
+evalArith val (Mul x y) = evalArith val x * evalArith val y
+evalArith _ (Const x) = x
+evalArith val (IVar s) = the (lookup s val)
+    where the (Just x) = x
 
 
 
@@ -50,12 +65,23 @@
 {- Aufgabe G8.4 -}
 
 mkTable :: Form -> [[String]]
-mkTable = undefined
+mkTable phi = firstRow : secondRow : map (zipWith align lengths . mkRow) (vals $ vars phi)
+  where
+    firstRow = vars phi ++ ["|", show phi]
+    secondRow = map (map (const '-')) firstRow
+    lengths = map length firstRow
 
+    mkRow val = map (stringOfBool . snd) val ++ ["|", stringOfBool $ eval val phi]
+
+    stringOfBool True = "T"
+    stringOfBool False = "F"
+
+    align n xs = lpad ++ xs ++ rpad
+      where
+      (lpad, rpad) = splitAt ((n - length xs) `div` 2) (replicate (n - length xs) ' ')
 
 showTable :: Form -> String
 showTable = unlines . map unwords . mkTable
 
-
 printTable :: Form -> IO ()
 printTable = putStrLn . showTable
\ No newline at end of file