我想從城市陣列中的所有資料中獲取溫度并以華氏度輸出資料。
我試過的一切似乎都不起作用,你可以看到 getAllTempsF 是我最近的嘗試。
C 到 F 為 (c*1.8) 18
data City = City { cityName :: String
, temperature :: [Double]
}
city1 = City {cityName = "city1", temperature = [4.50,6.50,5.0,6.48,8.54]}
city2 = City {cityName = "city2", temperature = [6.35,5.12,3.21,3.25,4.56]}
city3 = City {cityName = "city3", temperature = [7.3,5.32,4.4,4.6]}
cities :: [City]
cities = [city1,city2,city3]
getAllNames :: [City] -> [String]
getAllNames x = map cityName x
getAllTemps :: [City] -> [[Double]]
getAllTemps x = map temperature x
getAllTempsF :: [City] -> [[Double]]
getAllTempsF [] = 1
getAllTempsF (x:xs) = [((x * 1.8) 32)..] >> getAllTempsF xs
uj5u.com熱心網友回復:
您已經使用過map,這意味著“對串列的每個元素做一些事情”,在getAllTemps. getAllTempsF也可以表述為“對串列的每個元素做某事”,在這種情況下,“某事”是一些數學運算。唯一的區別是我們處理的是串列串列,而不是單個串列。我們仍然可以使用map來撰寫這個函式;我們只需要做兩次。
getAllTempsF :: [City] -> [[Double]]
getAllTempsF xs = map (map (\x -> x * 1.8 32)) $ getAllTemps xs
現在我們將它放在串列串列中。您提到了列印資料,為此我們將使用forM_,這有點像map,但用于副作用而不是值。
printOutTemps :: [City] -> IO ()
printOutTemps cities = do
-- Get each city, together with its temperatures in a list.
let cityData = zip cities (getAllTempsF cities)
-- For each one... do some IO.
forM_ cityData $ \(city, tempsF) -> do
-- Get the temperatures as a list of strings, so we can print them out.
let tempsStr = map show tempsF
-- Print out the city names and the temperatures.
putStrLn $ (cityName city) " has temperatures " unwords tempsStr
在線嘗試!
如果你還沒有找到這個特定的資源,Hoogle是一個很好的識別 Haskell 函式的站點。因此,如果您不知道我在此答案中使用的任何功能是做什么的,您可以隨時在 Hoogle 上搜索它們。例如,如果您不知道做什么zip,您可以搜索zip,第一個結果正是您要查找的功能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474045.html
標籤:哈斯克尔
