Getting average of calculated list haskell [duplicate]

℡╲_俬逩灬. 提交于 2019-12-11 13:51:12

问题


I have

avgRatingsForDirector :: String -> [Film] -> [Int]
avgRatingsForDirector _ [] = []
avgRatingsForDirector requestedDirector ((Film _ director _ ((_, rating):ratings)):restOfFilms)
    | requestedDirector == director = [rating] ++ avgRatingsForDirector requestedDirector restOfFilms
    | otherwise = avgRatingsForDirector requestedDirector restOfFilms

This outputs a list of numbers, I want to have the result be the average of these numbers. is is possible to use the foldr function on the result somehow?


回答1:


You can keep your function as is and post-process its result with a function to calculate an average of any list of numbers.

One way to code it so it does only one traversal of the list is

{-# LANGUAGE BangPatterns #-}
import Data.List

avg :: (Integral a, Fractional b) => [a] -> b
avg xs = g $ foldl' c (0,0) xs
 where
   c (!a,!n) x = (a+x,n+1)
   g (a,n) = fromIntegral a / fromIntegral n

Bang patterns make the calculation efficient.

see also: The Most Fuun You Can Have: Beautiful Folding



来源:https://stackoverflow.com/questions/21997609/getting-average-of-calculated-list-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!