Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading