{- Answers to Haskell Mini Exercises #2 -} module Mini2 where import Data.Char -- pointfree function rev_square that takes a list -- of integers and returns their squares, in reverse order. rev_square :: [Integer] -> [Integer] rev_square = reverse . map (^2) {- If you had trouble figuring this out, here is a step-by-step version. First, we want to take a list of numbers and find their squares. This calls for map - use a section rather than a lambda for the square function: map (^2) Then reverse the result. If we don't worry about making it pointfree, this is rev_square s = reverse (map (^2) s) To make it pointfree, we want the right hand side to be a single function applied to the argument s. So use compose: rev_square s = (reverse . map (^2)) s And now we can drop the s from both sides. -} -- concatenate a list of lists concat' :: [[a]] -> [a] concat' = foldr (++) [] {- The following are correct types for member: member :: (Ord a) => a -> [a] -> Bool member :: (Eq a) => a -> [a] -> Bool member :: (Eq a) => [a] -> [[a]] -> Bool member :: Bool -> [Bool] -> Bool This is the most general type for member: member :: (Eq a) => a -> [a] -> Bool -} -- inorder and postorder tree traversal functions data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show,Read) inorder :: Tree a -> [a] inorder EmptyTree = [] inorder (Node x left right) = inorder left ++ [x] ++ inorder right postorder :: Tree a -> [a] postorder EmptyTree = [] postorder (Node x left right) = postorder left ++ postorder right ++ [x] -- List is just like the built-in list type, but without such a nice syntax data List a = Empty | Cell a (List a) deriving (Show,Read) append :: List a -> List a -> List a append Empty ys = ys append (Cell x xs) ys = Cell x (append xs ys) mymap :: (a -> b) -> List a -> List b mymap f Empty = Empty mymap f (Cell x xs) = Cell (f x) (mymap f xs) -- some example lists x = Cell 1 (Cell 2 (Cell 3 Empty)) y = Cell 10 (Cell 11 Empty) z = append x y m = mymap (*2) z capitalize = do s <- getLine putStrLn (map toUpper s) santa :: Integer -> IO () santa n = if n>0 then do putStrLn "ho" santa (n-1) else return () {- print the square root of 2. Converted from printsqrt2 = do putStr "the square root of 2 is " putStrLn (show (sqrt 2)) -} printsqrt2 = putStr "the square root of 2 is " >> putStrLn (show (sqrt 2)) {- read in x and calculate its square root. Converted from: calcsqrt = do x <- readLn putStrLn "calculating the square root of x" putStrLn (show (sqrt x)) -} calcsqrt = readLn >>= \x -> putStrLn "calculating the square root of x" >> putStrLn (show (sqrt x))