Exercises Solutions
http://en.wikibooks.org/wiki/Haskell/YAHT
Exercise 3.10
Save the following scripts in SumInputs.hs:
module Main where main = do inputNumbers <- getNumber putStrLn ("The sum is " ++ show (sum inputNumbers)) putStrLn ("The product is " ++ show (foldr (*) 1 inputNumbers)) printFactorials inputNumbers getNumber = do putStrLn "Give me a number (or 0 to stop): " number <- getLine let num = read number if num == 0 then return [] else do rest <- getNumber return (num : rest) printFactorials [] = putStrLn "" printFactorials (x:xs) = do putStrLn (show x ++ " factorial is: " ++ show (factorial x)) printFactorials xs factorial 1 = 1 factorial n = n * factorial (n-1)
-
Run it in ghci: main
-
Compile and run in console:
ghc --make SumInputs.hs -o myfac
./myfac
Exercise 4.4 & 4.5
data Pair a b = Pair a b pairFst (Pair x y) = x pairSnd (Pair x y) = y data Triple a b c = Triple a b c tripleFst :: Triple a b c -> a tripleFst (Triple a b c) = a tripleSnd (Triple a b c) = b tripleThr (Triple a b c) = c data Quadruple a b = Quadruple a a b b deriving (Show) firstTwo :: Quadruple a b -> [a] -- you can't write it as: ... -> [a, a]. This is not a valid type expression? firstTwo (Quadruple w x y z) = [w, x]
lastTwo :: Quadruple a b -> [b] lastTwo (Quadruple w x y z) = [y, z]
Exercise 4.6
data Tuple a b c d = Tuple1 a | Tuple2 a b | Tuple3 a b c | Tuple4 a b c d deriving (Show) tuple1 :: Tuple a b c d -> a tuple1 (Tuple1 x) = x tuple1 (Tuple2 x y) = x tuple1 (Tuple3 x y z) = x tuple1 (Tuple4 x y z t) = x tuple2 :: Tuple a b c d -> Maybe b tuple2 (Tuple1 x) = Nothing tuple2 (Tuple2 x y) = Just y tuple2 (Tuple3 x y z) = Just y tuple2 (Tuple4 x y z t) = Just y tuple3 :: Tuple a b c d -> Maybe c tuple3 (Tuple1 x) = Nothing tuple3 (Tuple2 x y) = Nothing tuple3 (Tuple3 x y z) = Just z tuple3 (Tuple4 x y z t) = Just z tuple4 :: Tuple a b c d -> Maybe d tuple4 (Tuple1 x) = Nothing tuple4 (Tuple2 x y) = Nothing tuple4 (Tuple3 x y z) = Nothing tuple4 (Tuple4 x y z t) = Just t
Pattern matching plays a big role in tuple-like data structure.