这是问题:
"Write a function that computes the mean of a list, i.e. the sum of all elements in the list divided by its length. (You may need to use the fromIntegral function to convert the length of the list from an integer into a floating point number.)"
首先我尝试了这个:
mean :: [Double] -> Double
mean [] = 0
mean (x:xs) = (x + mean xs) / (1 + mean xs)
但它给了我奇怪的结果,例如,当我这样使用它时:
mean [2,4,6]
它给了我结果:1.41176
它应该在哪里:4
为什么?
我尝试了另一件事:
mean :: [Double] -> Double
mean list = (summ list) / (count list)
where count [] = 0
count (x:xs) = 1 + count xs
summ [] = 0
summ (x:xs) = x + summ xs
但是当我尝试将文件加载到 GHC 时出现错误。
错误是:
parse error on input 'count'
Failed, modules loaded: none
再说一遍,我做错了什么?
最后,我尝试了这个(成功了):
mean :: [Double] -> Double
count [] = 0
count (x:xs) = 1 + count xs
summ [] = 0
summ (x:xs) = x + summ xs
mean list = summ list / count list
它与上面的相同(带有'where'关键字),但它只在这里成功,而不是在上面的。
为什么?
非常感谢。
附注
我正在从这本书中学习——Real World Haskell
练习来自here --(向下滚动:-))
谢谢大家。 这是一件奇怪的事情。 当我从这里复制并测试它时,第二个示例也适用于我。 我不知道为什么它昨天对我不起作用:-)
但我仍然不明白为什么第一个不起作用。 我想应该是这样的
(2 + mean [4,6]) / (1 + mean [4,6])
(4 + mean [6 ]) / (1 + mean [ 6])
(6 + mean [ ]) / (1 + mean [ ])
所以现在就是这样
(6 + 0 ) / (1 + 0 ) -- last recursion
(4 + (6 + 0) ) / (1 + (1 + 0) )
(2 + (4 + (6 + 0))) / (1 + (1 + (1 + 0))
所以现在应该是:12/3
不是吗?
我不明白什么?
谢谢你:-)。
最佳答案
您第一次尝试时得到了错误的答案,因为您使用了不正确的公式。垃圾进垃圾出。 (其他人已经介绍过这一点。)
您可能会遇到解析错误,因为某些行使用空格而其他行使用制表符。或者您正在使用所有选项卡,但选项卡宽度非标准。
此处没有使用或不需要缩进,因此不会出现空格 -v- tabs 问题。
关于Haskell 学习练习给出了奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2027570/