-- Informatics 1 Functional Programming -- Mock exam -- -- Solutions import Data.Char import Test.QuickCheck -- Question 1 -- 1a. isFaceCard :: Char -> Bool isFaceCard x = x == 'A' || x == 'K' || x == 'Q' || x == 'J' isCard :: Char -> Bool isCard x = isFaceCard x || (isDigit x && x /= '1') f :: String -> Bool f str = and [ isFaceCard c | c <- str, isCard c ] -- 1b. g :: String -> Bool g [] = True g (c:str) | isCard c = isFaceCard c && g str | otherwise = g str -- 1c. h :: String -> Bool h str = foldr (&&) True (map isFaceCard (filter isCard str)) prop_fg :: String -> Bool prop_fg str = f str == g str prop_fh :: String -> Bool prop_fh str = f str == h str -- Question 2 -- 2a. t :: [a] -> [a] t xs = concat [ if odd i then [x] else [x,x] | (x,i) <- zip xs [1..] ] -- 2b. u :: [a] -> [a] u [] = [] u [x] = [x] u (x:y:xs) = x : y : y : u xs prop_tu1 :: String -> Bool prop_tu1 str = t str == u str prop_tu2 :: [Int] -> Bool prop_tu2 xs = t xs == u xs -- Question 3 data Chars = Range Char Char | Union Chars Chars | Complement Chars -- 3a. showChars :: Chars -> String showChars (Range c d) = "[" ++ [c] ++ "-" ++ [d] ++ "]" showChars (Union x y) = "(" ++ showChars x ++ "|" ++ showChars y ++ ")" showChars (Complement x) = "~" ++ showChars x -- 3b. inChars :: Chars -> Char -> Bool inChars (Range c d) ch = c <= ch && ch <= d inChars (Union x y) ch = inChars x ch || inChars y ch inChars (Complement x) ch = not (inChars x ch)