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
CodePudding user response:
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)