module Sol_Exercise_2 where import Data.List import Test.QuickCheck {- G1 -} all_sums :: [Integer] -> [Integer] -> [Integer] all_sums xs ys = [x + y | x <- xs, y <- ys] evens :: [Integer] -> [Integer] evens xs = [x | x <- xs, x `mod` 2 == 0] n_lists :: [Integer] -> [[Integer]] n_lists xs = [[1..x] | x <- xs] all_even_sum_lists :: [Integer] -> [Integer] -> [[Integer]] all_even_sum_lists xs ys = [[1..x+y] | x <- xs, y <- ys, (x + y) `mod` 2 == 0] prop_all_even_sum_lists xs ys = all_even_sum_lists xs ys == n_lists (evens (all_sums xs ys)) {- G2 -} union :: [Integer] -> [Integer] -> [Integer] union xs ys = xs ++ ys intersection :: [Integer] -> [Integer] -> [Integer] intersection xs ys = [x | x <- xs, y <- ys, x == y] diff :: [Integer] -> [Integer] -> [Integer] diff xs ys = [x | x <- xs, not (x `elem` ys)] elem' :: Integer -> [Integer] -> Bool elem' x xs = not (null [y | y <- xs, y == x]) prop_inter_1 x xs ys = x `elem` xs ==> x `elem` ys ==> x `elem` intersection xs ys prop_inter_2 x xs ys = x `elem` intersection xs ys ==> x `elem` xs && x `elem` ys prop_inter_3 x xs ys = (x `elem` xs && x `elem` ys) == (x `elem` intersection xs ys) {- G3 -} eq_frac :: (Integer,Integer) -> (Integer,Integer) -> Bool eq_frac (a,b) (c,d) = a*d == c * b prop_eq_frac_scale a b n = eq_frac (a, b) (n * a, n * b) prop_eq_frac_refl a b = eq_frac (a, b) (a, b) {- G4 -} pow2_slow :: Integer -> Integer pow2_slow 0 = 1 pow2_slow n | n > 0 = 2 * pow2_slow (n - 1) pow2 :: Integer -> Integer pow2 0 = 1 pow2 n | n < 0 = undefined | n `mod` 2 == 0 = k * k | otherwise = 2 * pow2 (n - 1) where k = pow2 (n `div` 2) {- H1 -} count :: [Char] -> Char -> Integer count cs c = genericLength [c' | c' <- cs, c' == c] count' :: [Char] -> Char -> Integer count' cs c = sum [1 | c' <- cs, c' == c] {- H2 -} reverseLookup :: Integer -> [(String, Integer)] -> [String] reverseLookup val tab = [k | (k,v) <- tab, v == val] prop1 tab1 tab2 name size = name `elem` reverseLookup size (tab1 ++ (name,size) : tab2) prop2 tab size = [x | x <- [(n,size) `elem` tab | n <- res], not x] == [] where res = reverseLookup size tab {- H3 -} wordsOfLength :: [Char] -> Integer -> [[Char]] wordsOfLength alphabet n = wol (nub alphabet) n where wol as 0 = [""] wol as n = [[a] ++ s | a <- as, s <- wol as (n - 1)] {- H4 -} {-WETT-} palindromesOfRadius :: [Char] -> Integer -> [[Char]] palindromesOfRadius alphabet radius = (if radius == 0 then [] else palindromesOfRadius alphabet' (radius - 1)) ++ [w ++ reverse w | w <- wordsOfLength alphabet' radius] ++ [w ++ [a] ++ reverse w | w <- wordsOfLength alphabet' radius, a <- alphabet'] where alphabet' = nub alphabet {-TTEW-}