import Data.List hiding ( findIndex ) ------------------------------------------------------------------------------ -- 1 findIndex :: Eq a => a -> [a] -> Int findIndex x (y:ys) | x == y = 0 | otherwise = 1 + findIndex x ys ------------------------------------------------------------------------------ -- 2 extension :: String -> String extension = ("."++) . reverse . takeWhile (/='.') . reverse {- -- or: extension s = "." ++ reverse (takeWhile (/='.') (reverse s)) -} ------------------------------------------------------------------------------ -- 3 data Form = And Form Form | Or Form Form | Not Form | Val Bool 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 x) = x ------------------------------------------------------------------------------ -- 4 prop_AllEqual :: [Int] -> Bool prop_AllEqual xs = and [ all (y==) ys | y:ys <- group xs ] {- -- or: prop_AllEqual xs = and [ length (nub ys) == 1 | ys <- group xs ] -} {- -- or: prop_AllEqual xs = and [ y == z | y:ys <- group xs, z <- ys ] -} prop_Original :: [Int] -> Bool prop_Original xs = concat (group xs) == xs ------------------------------------------------------------------------------ -- 5 yesNoQuestion :: String -> IO Bool yesNoQuestion s = do putStr (s ++ " ") s <- getLine return (s == "yes") ------------------------------------------------------------------------------ -- 6 type Snake = [String] snake :: [String] -> Snake snake ws = longest [ snakeWith c ws | c <- nub (map head ws) ] snakeWith :: Char -> [String] -> Snake snakeWith c ws = longest [ w : snakeWith (last w) (ws \\ [w]) | w <- ws , head w == c ] longest :: [Snake] -> Snake longest = snd . maximum . ((0,[]):) . map (\xs -> (length xs, xs)) {- -- or: longest [] = [] longest xs = snd (maximum [ (length x, x) | x <- xs ]) -} ------------------------------------------------------------------------------ -- 7 data Diagram = Question String Diagram Diagram | Action String Diagram | Done example :: Diagram example = Question "Is it raining?" (Action "Buy an umbrella." (Question "Still getting wet?" (Action "Buy a rain coat." Done) Done)) (Question "Is the sun shining?" (Action "Buy sun glasses." (Action "Go to the beach." Done)) (Action "Stay at home." Done)) type Action = String follow :: Diagram -> IO [Action] follow (Question q yes no) = do ans <- yesNoQuestion q if ans then follow yes else follow no follow (Action act d) = do putStrLn act acts <- follow d return (act:acts) follow Done = do return [] ------------------------------------------------------------------------------