當您沿着列表行進時,分別跟蹤每個性別的總計身高和數量(人口),然後在列表末尾將總計身高除以每個性別的計數以得到平均身高每個性別:
import Data.Ratio ((%))
averages :: [(String, Integer)] -> (Rational, Rational)
averages = go 0 0 0 0
where
rat :: Integer -> Integer -> Rational
rat 0 0 = 0
rat n d = n % d
go :: Integer -> Integer -> Integer -> Integer -> [(String, Integer)] -> (Rational, Rational)
go fHeight fCount mHeight mCount [] = (rat fHeight fCount, rat mHeight mCount)
go fHeight fCount mHeight mCount (("Female", height):xs) = go (fHeight + height) (fCount + 1) mHeight mCount xs
go fHeight fCount mHeight mCount (("Male", height):xs) = go fHeight fCount (mHeight + height) (mCount + 1) xs
這給:
> averages [("Female", 120), ("Male", 160), ("Female", 180)]
(150 % 1,160 % 1)