batat
batat

Reputation: 33

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

Upvotes: 2

Views: 78

Answers (2)

czheo
czheo

Reputation: 1941

You need to change coldestAvg [] = 0 to coldestAvg [] = 1/0

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

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)

Upvotes: 4

Related Questions