About
set1 q1toCatYears :: Float -> Float toCatYears n | n <= 0 = abs n 15 | n <= 1 = 15 + n 9 | otherwise = 24 + (n - 2) * 4
main = do let n = -6 let catYears = toCatYears n putStrLn $ "A cat that is " ++ show n ++ " years old in human years is " ++ show catYears ++ " years old in cat years."
q2 reach :: [Int] -> Int reach xs = maximum xs - minimum xs
main = do let n = [3, 7, 2, 9, 4] let r = reach n putStrLn $ show r
set2
q1
divisors :: Int -> Int
divisors n = length [x | x <- [1..n], n mod
x == 0]
main = do
let n = 25
let num_divisors = divisors n
putStrLn $ "The number of divisors of " ++ show n ++ " is " ++ show num_divisors
q2 replaceThird :: [(String, String, String)] -> [Double] -> [(String, String, Double)] replaceThird [] [] = [] replaceThird ((x, y, _):xs) (d:ds) = (x, y, d) : replaceThird xs ds
main = do let lst1 = [("apple", "banana", "carrot"), ("dog", "cat", "fish"), ("red", "green", "blue")] let lst2 = [1.2, 3.4, 5.6] let replaced = replaceThird lst1 lst2 putStrLn $ "Original list: " ++ show lst1 putStrLn $ "Replaced list: " ++ show replaced
set3 q1
runningTotal :: Num a => [a] -> [a] runningTotal xs = scanl1 (+) xs
main = do let nums = [1, 2, 3, 4] let result = runningTotal nums putStrLn $ "Running total of " ++ show nums ++ ": " ++ show result
q2
replaceThird :: [(String, String, String)] -> [Double] -> [(String, String, Double)] replaceThird [] [] = [] replaceThird ((x, y, _):xs) (d:ds) = (x, y, d) : replaceThird xs ds
main = do let lst1 = [("apple", "banana", "carrot"), ("dog", "cat", "fish"), ("red", "green", "blue")] let lst2 = [1.2, 3.4, 5.6] let replaced = replaceThird lst1 lst2 putStrLn $ "Original list: " ++ show lst1 putStrLn $ "Replaced list: " ++ show replaced
Foldl sum' :: (Num a) => [a] -> a sum' xs = foldl (\acc x -> acc + x) 0 xs
Foldr map' :: (a -> b) -> [a] -> [b] map' f xs = foldr (\x acc -> f x : acc) [] xs
zip zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c] zipWith' _ [] _ = [] zipWith' _ _ [] = [] zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
Chain
chain :: (Integral a) => a -> [a]
chain 1 = [1]
chain n
| even n = n:chain(n div
2)
| odd n =n:chain(n*3+1)