Pattern-matching on values
vowel :: Char -> Bool vowel 'a' = True vowel 'e' = True vowel 'i' = True vowel 'o' = True vowel 'u' = True vowel _ = False
Count the length of a collatz sequence starting from
n. See also the assignment 1 solutions. Note that those are backquotes on the
`div` – some of you are getting that wrong. Also, pay attention to the difference between
`div` (integer division) and
/ (float, or fractional division).
collatzCount :: Int -> Int collatzCount n | n <= 1 = 0 | even n = collatzCount (n `div` 2) + 1 | otherwise = collatzCount (3*n+1) + 1
A really simple function that works on any numeric type (class
squared x = x*x
A main function, using the
do notation and output statements (side effects).
main = do putStrLn "Hello there" putStrLn "Haskell is fun"
Produce a list with
count copies of a given value
genList :: a -> Int -> [a] genList elem count | count == 0 =  | otherwise = elem : genList elem (count-1)
genList 3 5⇒
genList 'a' 8⇒
genList 'x' 0⇒
Produce a range of integers (much like the built-in notation
[3..8] which is syntactic sugar for a function
fromTo :: Int -> Int -> [Int] fromTo start end | end < start =  | otherwise = start : fromTo (start+1) end
fromTo 3 8⇒
fromTo 10 14⇒
fromTo 10 8⇒
Duplicate each element of the list.
dupe :: [a] -> [a] dupe  =  dupe (h:t) = h : h : dupe t
Square each element of a list, using direct recursion. (A more idiomatic approach would be to use
squares  =  squares (h:t) = h*h : squares t