{- Haskell exercises from Fall 2016 -} -- 10 points, should be the same as a function with different name on cheat sheet -- exercise 1 myElem:: Eq a => a -> [a] -> Bool myElem _ [] = False myElem anItem (x:xs) = if anItem == x then True else myElem anItem xs -- 15 points -- can also do this with recursion and a cons operator : -- exercise 2 myReplicate:: Int -> a -> [a] myReplicate n anItem = [anItem | i <- [1..n]] -- 20 points -- can use a loop for this, too -- if they use `div` instead of fromIntegral, that's okay -- exercise 3 halve:: [a] -> ([a],[a]) halve [] = ([],[]) halve aList = (take firstHalf aList, drop firstHalf aList) where firstHalf = ceiling (fromIntegral (length aList)/2) -- 15 points -- the predicate a [(Int,Int,Int)] pyths n = [(a,b,c) | a <- [1..n], b <- [1..n], c <- [1..n], a [a] -> [a] -> [a] merge aList [] = aList merge [] aList = aList merge aList@(a:as) bList@(b:bs) = if a < b then [a] ++ merge as bList else [b] ++ merge aList bs -- exercise 6 -- 20 points -- next time, I will teach fromIntegral -- mergesort msort:: Ord a => [a] -> [a] msort aList = if length aList <= 1 then aList else merge (msort (take n aList)) (msort (drop n aList)) where n = ceiling (fromIntegral (length aList)/2) -- having a demonstration function like this is optional -- but I found it convenient main = do putStrLn "Haskell Exercises for CMSC 331, Fall 2016" putStrLn "Exercise 1 myElem" putStrLn (show(myElem 2 [1,2,3])) putStrLn "should be True" putStrLn (show(myElem 4 [1,2,3])) putStrLn "should be False" putStrLn "Exercise 2 myReplicate" putStrLn (show(myReplicate 3 "tsk")) putStrLn "Exercise 3 halve" putStrLn (show(halve [31,41,5,9,26])) putStrLn "Exercise 4 Pythagorean Triples" putStrLn (show(pyths 20)) putStrLn "Exercise 5 Merge two lists" putStrLn (show(merge [1,3,5] [2,4,6,8])) putStrLn "that should be sorted" putStrLn "Exercise 6 Mergesort" putStrLn (show(msort [31,41,5,9,26])) putStrLn "That's all"