-- sample solutions for Revision Tutorial 3, 28 Nov 2012 import Test.QuickCheck -- Problem 2010 resit - 2 f1 :: [a] -> [a] f1 xs = [xs !! i | i <- [0,3..length xs - 1]] g1 :: [a] -> [a] g1 [] = [] g1 (x:y:z:rest) = x : g1 rest g1 small_list = [head small_list] h1 :: [a] -> [a] h1 xs = map (\i -> xs !! i) [0,3..length xs - 1] test1 = f1 "abcdefghij" == "adgj" && f1 [1, 2, 3, 4, 5] == [1, 4] && f1 [0, 0, 0, 0, 0] == [0, 0] && f1 ([]::[Integer]) == [] -- there is an ambiguity if [] is not casted prop1 :: Eq a => [a] -> Bool prop1 xs = f1 xs == g1 xs && f1 xs == h1 xs -- Problem 2009 sitting 2 - 2 f2 :: [a] -> [a] f2 xs = concat [[xs !! (i+1), xs !! i]| i <- [0,2..length xs - 1]] g2 :: [a] -> [a] g2 [] = [] g2 (x:y:rest) = y:x:(g2 rest) h2 :: [a] -> [a] h2 xs = concat (map (\i -> [xs !! (i+1), xs !! i]) [0,2..length xs - 1]) test2 = f2 "swapping" == "wspaipgn" && f2 [1, 2, 3, 4] == [2, 1, 4, 3] && f2 ([]::[Integer]) == [] prop2 :: (Eq a) => [a] -> Property prop2 xs = (even (length xs)) ==> f2 xs == g2 xs && f2 xs == h2 xs -- Problem 2011 - 2 f3 :: [Integer] -> Integer f3 xs | even (length xs) = sum [(xs !! i) * (xs !! (i+1)) | i <- [0,2..length xs - 2]] g3 :: [Integer] -> Integer g3 [] = 0 g3 (x:y:rest) = x * y + (g3 rest) h3 :: [Integer] -> Integer h3 xs | even (length xs) = foldr (+) 0 (map (\i -> (xs !! i) * (xs !! (i+1))) [0,2..length xs - 2]) test3 = f3 [1, 2, 3, 4] == 14 && f3 [3, 5, 7, 5, -2, 4] == 42 && f3 [] == 0 -- f3 [1, 2, 3] gives an error prop3 :: [Integer] -> Property prop3 xs = even (length xs) ==> f3 xs == g3 xs && f3 xs == h3 xs