我已经编写了一个简单的函数来显示:地名、北度、东度和降雨量列表。
如何获得某个地方的平均降雨量?例如,在我的代码中,如何获得伦敦的平均降雨量?
抱歉,如果我的代码不是最好的,我只是在学习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发布于 2020-04-22 23:10:31
除了对Andrew Ray的解释之外,我认为用代码提供一个可用的示例可能会有所帮助:
module Lib
( avgRainLevel
, rainLevels
, testData
) where
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])]
findPlace :: [Place] -> String -> Place
findPlace placeList place = head . filter isPlace $ placeList
where isPlace (name, _, _, _) = name == place
getLevel :: Place -> [Int]
getLevel (_, _, _, levels) = levels
rainLevels :: [Place] -> String -> [Int]
rainLevels placeList place = getLevel $ findPlace placeList place
average :: [Int] -> Float
average ints = fromIntegral levelSum / fromIntegral count
where levelSum = sum ints
count = length ints
avgRainLevel :: [Place] -> String -> Float
avgRainLevel placeList place = average $ rainLevels placeList place我有点不确定你想要得到的实际值是什么。根据名称rainLevels,我得出的结论是您需要雨量列表,因此我将类型调整为[Int]。因为您不仅提供了位置列表,还提供了要查询的实际位置,所以我必须添加另一个参数,该参数将一个-> String添加到函数的类型声明中。
基于该函数,我执行了另一个函数avgRainLevel,它计算类型为[Int]的列表中的值的平均值。
代码将会像文档中描述的那样使用这些测试:
import Lib (rainLevels, avgRainLevel, testData)
import Test.Hspec (Spec, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = do
it "can read the list of levels" $ do
let levels = rainLevels testData "London"
levels `shouldBe` [0, 0, 5, 8, 8, 0, 0]
it "can calculate the average rain level" $ do
let avg = avgRainLevel testData "Norwich"
avg `shouldBe` 2请注意,实际上您不应该从这两个函数中的任何一个返回[Int]或Float。当您查询一个不在位置列表中的位置时,该代码将会死机。你最好返回Maybe [Int]和Maybe Float。在这种情况下,当您没有关于给定地点的信息时,可以返回Nothing。
https://stackoverflow.com/questions/61365035
复制相似问题