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).

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.

## Recent Comments