When teaching programming theory it is best to apply some of the concepts as practical examples. Often teachers neglect one area or the other but pupils need to see how both elements relate. Teaching content from any of the previous posts should be punctuated with appropriate examples but it is now a good point to try and draw lists and functions together into more concrete examples that apply the skills learnt so that we can solve problems.
The activities below get progressively more difficult and the solutions provided represent only one method that could be employed (and perhaps not always the best way of doing it!) The examples consider only what has been covered so far and this is intentional as we want reinforce and embed these basic concepts before moving on.
1. Over a 5 hour period the number of people riding on a roller coaster is recorded. After each hour the results are recorded as 12, 33, 9, 2 and 53. Create a function that accepts a list of these values and returns the first value (without using the head function).
firstNum :: [Integer] -> Integer firstNum xs = xs !! 0 -- xs is used to refer to all the x'es but it could have been any identifier of our choosing.
2. Modify the function so that it checks for an empty list and returns an error using the command error “No one rode the roller coaster”.
firstNum :: [Integer] -> Integer firstNum  = error "No one rode the roller coaster" firstNum xs = xs !! 0
3. Create a second function that returns the amount of people who rode on the roller coaster in the final hour.
lastNum :: [Integer] -> Integer lastNum = error "No one rode the roller coaster" lastNum xs = xs !! (length xs -1)
4. Create another function that returns the average number of people riding the roller coaster each hour using the data in the list. Hint: sum adds all elements of a list and division will need the numerator and denominator converting to fractional numbers (the / function only works on these) using fromIntegral eg: fromIntegral(theNumVariable).
averageNum :: [Integer] -> Double averageNum  = error "No one rode the roller coaster" averageNum xs = fromIntegral(sum xs) / fromIntegral (length xs)
5. The roller coaster has a regular maintenance hour where no people can ride on it for an hour. Create a function that can appropriately update the list when called during this hour.
maintHour :: [Integer] -> [Integer] maintHour xs = xs ++ 
6. The average for Saturday and Sunday is calculated together. Create a function that takes two lists of results and finds the average.
weekendAv :: [Integer] -> [Integer] -> Double weekendAv xs ys = fromIntegral(sum xs + sum ys) / fromIntegral(length xs + length ys)]