![](/img/trans.png)
[英]Java and data structures (Map, Hashmap, List, Arraylist, …)
[英]map function to newtype defined as a List of Data structures
我是Haskell和FP的新手,我正在通過LYAH和其他來源工作,但要“邊做邊學”,我正在嘗試編寫一個涉及JSON解析的小程序。 但是,我已將自己編入角落,無法離開。 我的代碼是從各種教程中拼湊而成的,我可以感覺到我仍然“在程序上思考”如何將它整合在一起,但我還沒有達到必要的突破才能使它工作。
首先,這是一個多級JSON文件的簡化版本,它是Weather Underground API的天氣預報,減少到三個小時。
{
"response": {
"version": "0.1",
"termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"hourly": 1
}
},
"hourly_forecast": [{
"FCTTIME": {
"hour": "8",
"epoch": "1479736800",
"pretty": "8:00 AM CST on November 21, 2016"
},
"temp": {
"english": "27",
"metric": "-3"
},
"condition": "Partly Cloudy"
}, {
"FCTTIME": {
"hour": "9",
"epoch": "1479740400",
"pretty": "9:00 AM CST on November 21, 2016"
},
"temp": {
"english": "32",
"metric": "0"
},
"condition": "Partly Cloudy"
}, {
"FCTTIME": {
"hour": "10",
"epoch": "1479744000",
"pretty": "10:00 AM CST on November 21, 2016"
},
"temp": {
"english": "35",
"metric": "2"
},
"condition": "Clear"
}]
}
接下來,這是我的Haskell程序。 我成功地解析JSON成newtype
稱為ForecastPointCollection
其定義為一個List
的WeatherPoint
,這是一個data
的,從JSON文件來各種事物的結構。 但是,我無法弄清楚如何將[WeatherPoint]
列表退出(參見代碼注釋)。 作為對列表中“要做的事情”的測試,我想將Celcius溫度轉換為開爾文並獲得一個我可以使用的新List
(輸出到JSON,做一個show
,等等)。
{-# LANGUAGE OverloadedStrings #-}
-- {-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Data.Aeson
import Data.Aeson.Types
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Text as T
import qualified Data.Vector as V
type MetricTemperature = Int
type KelvinTemperature = Int
newtype ForecastPointCollection = ForecastPointCollection
{forecastpointcollection :: [WeatherPoint]} deriving Show
data WeatherPoint = WeatherPoint
{ epoch :: T.Text
, prettyTime :: T.Text
, tempMetric :: MetricTemperature
, condition :: T.Text
} deriving Show
instance FromJSON ForecastPointCollection where
parseJSON (Object o) =
ForecastPointCollection <$> o .: "hourly_forecast"
parseJSON _ = mzero
data ProcessedWeatherPoint = ProcessedWeatherPoint
{ newEpoch :: T.Text
, newPrettyTime :: T.Text
, newTempKelvin :: KelvinTemperature
, newCondition :: T.Text
} deriving Show
instance FromJSON WeatherPoint where
parseJSON =
withObject "Root Object Arbitrary Name" $ \o -> do
fctO <- o .: "FCTTIME"
epoch <- fctO .: "epoch" -- contained within FCTTIME
pretty <- fctO .: "pretty" -- contained within FCTTIME
tempO <- o .: "temp"
metric <- tempO .: "metric" -- contained within temp
condition <- o .: "condition" -- at top level under hourly_forecast
return $ WeatherPoint epoch pretty (read metric) condition
-- parseJSON _ = mzero
kelvinizeTemp :: MetricTemperature -> KelvinTemperature
kelvinizeTemp x = x + 273 -- hey, close enough
adjustTemp :: Maybe ForecastPointCollection -> [ProcessedWeatherPoint]
adjustTemp Nothing = []
adjustTemp x = [] -- HERE IS WHERE I AM LOSING MY WAY!
-- HOW CAN I WALK THROUGH THE LIST INSIDE ForecastPointCollection
-- TO map kelvinizeTemp ACROSS THAT LIST AND
-- GET A [ProcessedWeatherPoint] LIST BACK TO PLAY WITH?
getSampleForecast = BSL.readFile "/home/mypath/test/forecastsubmit.json"
main = do
textOfJson <- getSampleForecast
let (forecasts2 :: Maybe ForecastPointCollection) = decode textOfJson
case forecasts2 of
Just (ForecastPointCollection forecasts2) -> do
putStrLn ("Success!")
putStrLn . show $ forecasts2
_ -> putStrLn "Could not parse ForecastPointCollection JSON correctly."
-- So far so good, we've extracted data from the JSON and stored it in memory.
-- But now, how can we manipulate that data and start doing stuff with it?
-- Currently, the "adjustTemp" function returns an empty list no matter what.
let (processed2 :: [ProcessedWeatherPoint]) = adjustTemp forecasts2
putStrLn ("More success (OK, not really, yet)!")
putStrLn . show $ processed2
任何建議表示贊賞 我不應該讓ForecastPointCollection
一個newtype
? 我在哪里慣用,我在哪里愚蠢? :-P
基於答案更新:對於后代,這里是新定義的processWeatherPoint函數的可能(工作)實現。 應該將data
結構的各個部分視為一個功能!
processWeatherPoint :: WeatherPoint -> ProcessedWeatherPoint
processWeatherPoint x = ProcessedWeatherPoint
(epoch x)
(prettyTime x)
(kelvinizeTemp (tempMetric x))
(condition x)
kelvinizeTemp :: MetricTemperature -> KelvinTemperature
kelvinizeTemp x = x + 273 -- this works OK because both types are type of Int
它應該足以定義一個函數......
processWeatherPoint :: WeatherPoint -> ProcessedWeatherPoint
...使用[WeatherPoint]
的[WeatherPoint]
提取字段,並將該函數映射到列表上:
adjustTemp :: Maybe ForecastPointCollection -> [ProcessedWeatherPoint]
adjustTemp Nothing = []
adjustTemp (Just (ForecastPointCollection points)) = processWeatherPoint <$> points
ForecastPointCollection
上的模式匹配的替代方法是使用該字段的記錄訪問器。 如果您不打算導出構造函數,那將特別有用:
adjustTemp :: Maybe ForecastPointCollection -> [ProcessedWeatherPoint]
adjustTemp Nothing = []
adjustTemp (Just forecast) = processWeatherPoint <$> forecastpointcollection forecast
一種可以說是更方便的編寫上面定義的方法涉及使用maybe
函數而不是對Maybe
進行明確的案例分析:
adjustTemp :: Maybe ForecastPointCollection -> [ProcessedWeatherPoint]
adjustTemp = maybe [] (fmap processWeatherPoint . forecastpointcollection)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.