在Haskell中有效地计算列表的均值 [英] Computing the mean of a list efficiently in Haskell
本文介绍了在Haskell中有效地计算列表的均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我设计了一个函数来计算列表的均值。虽然它工作正常,但我认为它可能不是最好的解决方案,因为它需要两个功能而不是一个。
I've designed a function to compute the mean of a list. Although it works fine, but I think it may not be the best solution due to it takes two functions rather than one. Is it possible to do this job done with only one recursive function ?
calcMeanList (x:xs) = doCalcMeanList (x:xs) 0 0
doCalcMeanList (x:xs) sum length = doCalcMeanList xs (sum+x) (length+1)
doCalcMeanList [] sum length = sum/length
推荐答案
您的解决方案很好,使用两个函数并不比一个更差。尽管如此,你可能会把尾递归函数放在其中
子句中。
Your solution is good, using two functions is not worse than one. Still, you might put the tail recursive function in a where
clause.
但是,如果你想在一行:
But if you want to do it in one line:
calcMeanList = uncurry (/) . foldr (\e (s,c) -> (e+s,c+1)) (0,0)
这篇关于在Haskell中有效地计算列表的均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文