Computing the mean of a list efficiently in Haskell

后端 未结 6 1932
傲寒
傲寒 2021-02-04 11:21

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

6条回答
  •  春和景丽
    2021-02-04 12:01

    When I saw your question, I immediately thought "you want a fold there!"

    And sure enough, a similar question has been asked before on StackOverflow, and this answer has a very performant solution, which you can test in an interactive environment like GHCi:

    import Data.List
    
    let avg l = let (t,n) = foldl' (\(b,c) a -> (a+b,c+1)) (0,0) l 
                in realToFrac(t)/realToFrac(n)
    
    avg ([1,2,3,4]::[Int])
    2.5
    avg ([1,2,3,4]::[Double])
    2.5
    

提交回复
热议问题