问题
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