如何修复我的 haskell 代码以适用于我的示例?

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

代码运行良好,但在我的示例中尝试时得到了错误的结果。问题是我示例中的这一部分:[-9..10]。此列 avarage 为 0.5,但我测试时得到 0。 haskell 在这个例子中使用空列表匹配模式,但我不知道为什么。我该如何解决这个问题?

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

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

您每次都使用列表的尾部 xs 进行递归调用。最终你会因此用空列表调用 coldestAvg,并且由于 0 在这种情况下是所有平均值中最小的,因此它将 return 0.

你不应该定义这样的基本情况:空列表没有最小值。对于只有一个元素的列表,你 return 平均值,所以:

coldestAvg :: [[Double]] -> Double
coldestAvg <strong>[x]</strong> = <strong>listAvg x</strong>
coldestAvg (x:xs) =  min (listAvg x) (coldestAvg xs)

您需要将 coldestAvg [] = 0 更改为 coldestAvg [] = 1/0