Here are the solutions to the exercises we solved in the Thursday tutorial.
In some cases I've renamed functions (e.g. last → last') to avoid conflicts with predefined functions in Haskell.
-- 1. Last Element
last' [x] = x
last' (_ : xs) = last' xs
-- 2. Second Last
secondLast [x, _] = x
secondLast (_ : xs) = secondLast xs
-- 3. Zip
zip' [] [] = []
zip' (x : xs) (y : ys) = (x, y) : (zip' xs ys)
-- 4. Unzip
unzip' [] = ([], [])
unzip' ((x, y) : ps) =
let (xs, ys) = unzip' ps
in (x : xs, y : ys)
-- 5. Flatten
flatten [] = []
flatten (l : ls) = l ++ (flatten ls)
-- 6. Reverse
reverse' l = reverse2 l []
reverse2 [] a = a
reverse2 (x : xs) a = reverse2 xs (x : a)
-- 7. Infinite Ints
intsFrom i = i : (intsFrom (i + 1))
ints = intsFrom 1
-- 8. Cycle List
cycle' l = l ++ (cycle' l)
-- 9. Termination
--
-- (a) will not terminate; (b) and (c) will terminate
-- 10. Primality Test
isPrime n = isPrime' 2 n
-- Given that no integer less than i divides n, return true if n is prime.
isPrime' i n =
i * i > n ||
not (n `mod` i == 0) && isPrime' (i + 1) n