在Haskell中,如何从整数列表中获得平均浮点数? [英] In Haskell, how do I get an average float from a list of integers?

查看:33
本文介绍了在Haskell中,如何从整数列表中获得平均浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的函数来显示:地点名称,北度,东度以及降雨数字列表.

I have written a simple function that displays: Name of place, Degrees North, Degrees East, and a list of rainfall numbers.

如何获得特定地点的平均降雨量?例如,在我的代码中,如何获得伦敦的平均降雨量?

How do I get an average rainfall specific to a place? For example in my code, how do I get an average rainfall for London?

对不起,如果我的代码不是最好的,我就是在学习Haskell.

Sorry if my code is not the best, I'm just learning Haskell.

import Data.Char
import Data.List
type Place = (String, Float, Float, [Int])

testData :: [Place]
testData = [("London", 51.5, -0.1, [0, 0, 5, 8, 8, 0, 0]),
            ("Cardiff", 51.5, -3.2, [12, 8, 15, 0, 0, 0, 2]),
            ("Norwich", 52.6, 1.3, [0, 6, 5, 0, 0, 0, 3])]

rainLevels :: [Place] -> Float 
rainLevels level (_, _, _, numbers) = sum numbers / 7

推荐答案

要查找伦敦"的平均降雨量,您需要首先在列表中找到伦敦"的记录,然后平均其降雨量.

To find the average rainfall for "London", you need to first find the record for "London" in your list, then average its rainfall numbers.

getAvgRainLevel 使用特定城市的名称: name 和记录列表: xs ;它会通过其名称查找该城市的记录,然后计算该城市的平均降雨量.

getAvgRainLevel consumes a name of a specific city: name, and a list of records: xs; it finds the record of that city by its name, then calculates the average rainfall level for that city.

getAvgRainLevel name xs = fmap avg $ lookup name (sanitize xs)
  where
    sanitize = fmap (\(city, _, _, rainLevels) -> (city, rainLevels))
    avg = (/) <$> sum <*>  fromIntegral . length

这篇关于在Haskell中,如何从整数列表中获得平均浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆