Haskell Exercises
Time to practise! Each exercise has a starter playground that compiles and runs as-is, printing a placeholder result so you can see the expected format. Replace the placeholder code marked TODO, press ▶ Run, and compare your output with the "Expected" line. Open the solution only after you've given it a real try.
| # | Exercise | Topics |
|---|---|---|
| 1 | FizzBuzz | guards, mod, mapM_ |
| 2 | Count the vowels | strings, filter, elem |
| 3 | Run-length encoding | group, tuples, list comprehensions |
| 4 | Safe average | Maybe, folds |
| 5 | Word frequencies | Data.Map, composition |
| 6 | Binary tree | data types, recursion, Functor |
| 7 | Validate a form | Either, applicative style |
| 8 | Stack calculator | State, pattern matching |
1. FizzBuzz
Print the numbers from 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both.
Expected: 1, 2, Fizz, 4, Buzz, … ending with FizzBuzz.
fizzbuzz :: Int -> String
fizzbuzz n = show n -- TODO: use guards
main :: IO ()
main = mapM_ (putStrLn . fizzbuzz) [1 .. 15]1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Show solution
fizzbuzz :: Int -> String
fizzbuzz n
| n `mod` 15 == 0 = "FizzBuzz"
| n `mod` 3 == 0 = "Fizz"
| n `mod` 5 == 0 = "Buzz"
| otherwise = show nCheck 15 first: otherwise the mod 3 guard would catch it.
2. Count the vowels
Write countVowels that counts a e i o u in a string, ignoring case.
Expected: countVowels "Functional Programming" == 7 and countVowels "RHYTHM" == 0.
import Data.Char (toLower)
countVowels :: String -> Int
countVowels s = 0 -- TODO
main :: IO ()
main = do
print (countVowels "Functional Programming")
print (countVowels "RHYTHM")
print (countVowels "AEIOU aeiou")0
0
0
Show solution
countVowels :: String -> Int
countVowels = length . filter (`elem` "aeiou") . map toLowerExpected output: 7, 0, 10.
3. Run-length encoding
Compress a string into pairs of (character, count) for each run of equal characters.
Expected: encode "aaabccdddd" == [('a',3),('b',1),('c',2),('d',4)], and decode turns it back into the original.
import Data.List (group)
encode :: String -> [(Char, Int)]
encode s = [] -- TODO: use group
decode :: [(Char, Int)] -> String
decode pairs = "" -- TODO: use replicate
main :: IO ()
main = do
print (encode "aaabccdddd")
putStrLn (decode [('x', 2), ('y', 3)])
print (decode (encode "mississippi") == "mississippi")[]
False
Show solution
encode :: String -> [(Char, Int)]
encode s = [(head g, length g) | g <- group s]
decode :: [(Char, Int)] -> String
decode = concatMap (\(c, n) -> replicate n c)group never produces an empty group, so head is safe here.
4. Safe average
Write average :: [Double] -> Maybe Double that returns Nothing for an empty list. Compute the sum and the count in one pass with foldl'.
Expected: Just 2.5 for [1, 2, 3, 4] and Nothing for [].
import Data.List (foldl')
average :: [Double] -> Maybe Double
average xs = Nothing -- TODO
main :: IO ()
main = do
print (average [1, 2, 3, 4])
print (average [])
print (average [10])Nothing
Nothing
Nothing
Show solution
average :: [Double] -> Maybe Double
average [] = Nothing
average xs = Just (total / fromIntegral count)
where
(total, count) = foldl' step (0, 0 :: Int) xs
step (!s, !c) x = (s + x, c + 1)Expected output: Just 2.5, Nothing, Just 10.0.
5. Word frequencies
Return the n most common words of a text (lowercase, letters only), most frequent first, ties broken alphabetically.
Expected for the sample with n = 3: [("the",3),("cat",2),("a",1)].
import qualified Data.Map.Strict as Map
import Data.Char (toLower, isAlpha)
import Data.List (sortOn)
import Data.Ord (Down (..))
topWords :: Int -> String -> [(String, Int)]
topWords n text = [] -- TODO
main :: IO ()
main = print (topWords 3 "The cat saw the dog. A cat? The END!")[]
Show solution
topWords :: Int -> String -> [(String, Int)]
topWords n =
take n
. sortOn (\(w, c) -> (Down c, w))
. Map.toList
. Map.fromListWith (+)
. map (\w -> (w, 1))
. words
. map (\c -> if isAlpha c then toLower c else ' ')Replacing every non-letter with a space before words removes the punctuation.
6. Binary tree
Complete the Functor instance and the functions size and toList (in-order) for this tree.
Expected: size is 5, toList is [1,3,4,7,9], and fmap (* 10) gives [10,30,40,70,90].
data Tree a = Leaf | Node (Tree a) a (Tree a)
instance Functor Tree where
fmap _ _ = Leaf -- TODO
size :: Tree a -> Int
size _ = 0 -- TODO
toList :: Tree a -> [a]
toList _ = [] -- TODO
sample :: Tree Int
sample = Node (Node (Node Leaf 1 Leaf) 3 (Node Leaf 4 Leaf)) 7 (Node Leaf 9 Leaf)
main :: IO ()
main = do
print (size sample)
print (toList sample)
print (toList (fmap (* 10) sample))0
[]
[]
Show solution
instance Functor Tree where
fmap _ Leaf = Leaf
fmap f (Node l x r) = Node (fmap f l) (f x) (fmap f r)
size :: Tree a -> Int
size Leaf = 0
size (Node l _ r) = size l + 1 + size r
toList :: Tree a -> [a]
toList Leaf = []
toList (Node l x r) = toList l ++ [x] ++ toList r7. Validate a form
Build a User from three raw strings using applicative style. The name must be non-empty, the age a number from 0 to 130, and the email must contain @. Report the first error.
Expected: Right (User "Ada" 36 "ada@calc.org"), then Left "age must be a number from 0 to 130".
import Text.Read (readMaybe)
data User = User String Int String deriving Show
validName :: String -> Either String String
validName n = Right n -- TODO
validAge :: String -> Either String Int
validAge a = Right 0 -- TODO
validEmail :: String -> Either String String
validEmail e = Right e -- TODO
mkUser :: String -> String -> String -> Either String User
mkUser n a e = Left "TODO" -- TODO: User <gt; ... <*> ...
main :: IO ()
main = do
print (mkUser "Ada" "36" "ada@calc.org")
print (mkUser "Ada" "two hundred" "ada@calc.org")
print (mkUser "" "36" "nope")Left "TODO"
Left "TODO"
Left "TODO"
Show solution
validName :: String -> Either String String
validName "" = Left "name must not be empty"
validName n = Right n
validAge :: String -> Either String Int
validAge a = case readMaybe a of
Just n | n >= 0 && n <= 130 -> Right n
_ -> Left "age must be a number from 0 to 130"
validEmail :: String -> Either String String
validEmail e
| '@' `elem` e = Right e
| otherwise = Left "email must contain @"
mkUser :: String -> String -> String -> Either String User
mkUser n a e = User <gt; validName n <*> validAge a <*> validEmail eThe third call reports Left "name must not be empty": the first failure wins.
8. Stack calculator
Evaluate a postfix (Reverse Polish) expression such as "3 4 + 2 *" with a State [Int] stack. Numbers are pushed; +, - and * pop two values and push the result.
Expected: "3 4 + 2 *" gives 14 and "5 1 2 + 4 * + 3 -" gives 14.
import Control.Monad.State
push :: Int -> State [Int] ()
push x = modify (x :)
step :: String -> State [Int] ()
step token = return () -- TODO: handle "+", "-", "*" and numbers
evalRPN :: String -> Int
evalRPN input = case execState (mapM_ step (words input)) [] of
(top : _) -> top
[] -> 0
main :: IO ()
main = do
print (evalRPN "3 4 + 2 *")
print (evalRPN "5 1 2 + 4 * + 3 -")0
0
Show solution
binary :: (Int -> Int -> Int) -> State [Int] ()
binary op = do
stack <- get
case stack of
(b : a : rest) -> put (op a b : rest)
_ -> return () -- not enough operands: ignore
step :: String -> State [Int] ()
step "+" = binary (+)
step "-" = binary (-)
step "*" = binary (*)
step token = push (read token)Note the order in binary: the top of the stack is the second operand, so "5 3 -" is 5 - 3.
Test yourself
In FizzBuzz, why must the mod 15 guard come first?
- Guards are evaluated in random order
- The first true guard wins, and multiples of 15 are also multiples of 3
mod 15is faster- It doesn't matter
What does group "aabccc" return?
["aa","b","ccc"][('a',2),('b',1),('c',3)]"abc"["a","b","c"]
In User <gt; validName n <*> validAge a <*> validEmail e with Either, which error is returned if both name and email are invalid?
- Both errors combined
- The name error (the first failure)
- The email error (the last failure)
- No error