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

How can I fix my haskell code to work for my example?

The code is working well, but I got a wrong result when I try it for my example. The problem is this part in my example : [-9..10]. This columns avarage is 0.5, but I got 0 when I test it. The haskell use the empty list match pattern for this example, but I do not know why. How can I fix this ?

listAvg :: [Double] -> Double
listAvg [] = 0
listAvg x = (sum x)/fromIntegral(length x)

coldestAvg :: [[Double]] -> Double
coldestAvg [] = 0
coldestAvg (x:xs) =  min (listAvg x) (coldestAvg xs)

Example :
coldestAvg [[12,13],[-9..10]] == 0.5

>Solution :

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

The haskell use the empty list match pattern for this example, but I do not know why. How can I fix this ?

You each time make a recursive call with the tail xs of the list. Eventually you will thus call coldestAvg with the empty list, and since 0 is the smallest of all the averages in this case, it will thus return 0.

You should not define such base case: there is no minimum for an empty list. For a list with one element, you return the average, so:

coldestAvg :: [[Double]] -> Double
coldestAvg [x] = listAvg x
coldestAvg (x:xs) =  min (listAvg x) (coldestAvg 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