Home > Enterprise >  A function that returns the highest average from multiple lists of numbers
A function that returns the highest average from multiple lists of numbers

Time:11-08

I have to define a highestAverage :: [[Int]] -> Double function that returns the highest average from a list of lists containing numbers.

For example:

bestAverage [[3,1], [5,4,3], [], [5,5,5], [1,2,3]] == 5.0

I have already written a function that returns the average of a list.

listAverage :: [Int] -> Double
listAverage [] = 0.0
listAverage x = fromIntegral(sum x)/fromIntegral(length x)

My problem is that I can't figure out a way to have it do recursion. I always get errors when loading in my module. My code right now looks like this:

highestAverage :: [[Int]] -> Double
highestAverage [[]] = 0.0
highestAverage (x:xs) = max(listAverage x, listAverage xs)

CodePudding user response:

For a non-empty list you call the groupAvg on the first sublist x, and then determine the max between that value, and the recursive call on the tail of the list. The base case is a single sublist where we calculate the maxiumum:

highestAverage :: [[Int]] -> Double
highestAverage [x] = listAverage x
highestAverage (x:xs) = max (listAverage x) (highestAverage xs)

This function will not work for an empty list. If you want to return 0 for an empty list, you can alter the base case to:

highestAverage :: [[Int]] -> Double
highestAverage [] = 0
highestAverage (x:xs) = max (listAverage x) (highestAverage xs)

CodePudding user response:

You can simply map your function over the list and take the maximum:

maximum $ map listAverage [[3,1], [5,4,3], [], [5,5,5], [1,2,3]]

  • Related