如何修复我的 haskell 代码以适用于我的示例?
该代码运行良好,但是当我尝试示例时,我的结果错误。问题是我的示例中的这部分:[-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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您每次都使用列表的尾部
xs
进行递归调用。最终,您将使用空列表调用coldestAvg
,并且由于0
是本例中所有平均值中最小的,因此它将返回0
>。您不应该定义这样的基本情况:空列表没有最小值。对于包含一个元素的列表,您返回平均值,因此:
You each time make a recursive call with the tail
xs
of the list. Eventually you will thus callcoldestAvg
with the empty list, and since0
is the smallest of all the averages in this case, it will thus return0
.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 [] = 0
更改为coldestavg [] = 1/0
You need to change
coldestAvg [] = 0
tocoldestAvg [] = 1/0