import Data.Char import Data.List import Data.Maybe import Test.QuickCheck -- 1. Implement a function splitComma :: String -> (String,String) {- that splits a string at the first comma character. The comma itself should not be part of the result. You don't need to handle the case where the string does not contain a comma. Examples: *Main> splitComma "abc,123" ("abc","123") *Main> splitComma "Jeffery Wilkie,15" ("Jeffery Wilkie","15") Hint: Use the standard functions takeWhile and dropWhile. -} splitComma s = (takeWhile (/= ',') s , drop 1 $ dropWhile (/= ',') s) -- 2 parseDB :: String -> [(String,String)] parseDB s = [ splitComma line | line <- lines s] parseDB2 s = map splitComma (lines s) parseDB3 [] = [] parseDB3 cs = (front,takeWhile (/= '\n') back) : parseDB3 (drop 1 $ dropWhile (/= '\n') back) where (front,back) = splitComma cs parseDB4 cs = parse (lines cs) where parse [] = [] parse (line:lines) = splitComma line : parse lines {- Assume that you have a database of personal information stored as a text file in the following format: Ginger Willard,45 Brandon Durand,23 Jeffery Wilkie,15 Adele Winton,68 Judith Stevens,38 Using splitComma, implement a function -} -- parseDB :: String -> [(String,String)] {- That converts String representing a table: Ginger Willard,45 Brandon Durand,23 Jeffery Wilkie,15 into a list of pairs -} prop_parseDB = parseDB "Bob Hund,25\nBon Jovi,33\n" == [("Bob Hund","25"),("Bon Jovi","33")] -- 3 data Form = And Form Form | Or Form Form | Not Form | Val Bool ex3 = False || not True ex3D = Or (Val False) (Not (Val True)) eval :: Form -> Bool eval (And a b) = eval a && eval b eval (Or a b) = eval a || eval b eval (Not a) = not (eval a) eval (Val b) = b -- 4 prop_append as bs = as `isPrefixOf` (as ++ bs) where types = as :: [Int] -- 5 lookupDB :: FilePath -> String -> IO String lookupDB file name = do contents <- readFile file let result = lookup name (parseDB contents) return $ fromJust result -------------------------------------------------------------------------------- -- showTable cols = undefined myTable :: [[String]] myTable = [ ["Adam", "Bertil", "Cesar"] , ["Lilla My", "E.T.", "X"] , ["1", "2", "3"] ] {- First fix the width of each column, then use transpose to get a list of rows. You might find concat and unlines useful for turning the list of rows into a single string. -} showTable cols = putStr $ unlines $ map concat $ transpose filledCols where filledCols = map fix cols fix col = [ item ++ replicate (longest - length item) ' ' | item <- col ] where longest = 1 + maximum [length item | item <- col] -------------------------------------------------------------------------------- -- 7