List 将函数映射到定义为数据结构列表的新类型

List 将函数映射到定义为数据结构列表的新类型,list,haskell,aeson,newtype,List,Haskell,Aeson,Newtype,我是Haskell和FP的新手,正在通过LYAH和其他来源进行研究,但为了“边做边学”,我正在尝试编写一个涉及JSON解析的小程序。然而,我把自己关在了一个角落里,出不去了。我的代码是从各种教程中拼凑而成的,我可以感觉到我仍然在“按程序思考”如何很好地将其组合在一起,但我还没有取得必要的突破以使其工作 首先,这里是一个多层JSON文件的简化版本,它是来自地下天气API的天气预报,减少到三个小时 { "response": { "version": "0.1",

我是Haskell和FP的新手,正在通过LYAH和其他来源进行研究,但为了“边做边学”,我正在尝试编写一个涉及JSON解析的小程序。然而,我把自己关在了一个角落里,出不去了。我的代码是从各种教程中拼凑而成的,我可以感觉到我仍然在“按程序思考”如何很好地将其组合在一起,但我还没有取得必要的突破以使其工作

首先,这里是一个多层JSON文件的简化版本,它是来自地下天气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解析成一个名为
ForecastPointCollection
新类型
,它被定义为
WeatherPoint
列表,它是来自JSON文件的各种内容的
数据结构。但是,我不知道如何将
[WeatherPoint]
列表拿回来(参见代码注释)。作为对列表“有什么事要做”的测试,我想将Celcius温度转换为开尔文,并得到一个新的
list
,我可以使用它(输出到JSON,执行
show
on,随便什么)


定义一个函数就足够了

processWeatherPoint :: WeatherPoint -> ProcessedWeatherPoint
。。。从newtype中提取带有
[WeatherPoint]
的字段,并将函数映射到列表上:

adjustTemp :: Maybe ForecastPointCollection -> [ProcessedWeatherPoint]
adjustTemp Nothing = []
adjustTemp (Just (ForecastPointCollection points)) = processWeatherPoint <$> points
编写上述定义的一种可能更方便的方法是使用
maybe
函数,而不是对
maybe
进行明确的案例分析:

adjustTemp :: Maybe ForecastPointCollection -> [ProcessedWeatherPoint]
adjustTemp = maybe [] (fmap processWeatherPoint . forecastpointcollection)

这个答案非常有用(就像后来的“Just”编辑帮助它编译一样),我已经将它标记为已接受的答案。谢谢你善良的哈斯凯勒!
adjustTemp :: Maybe ForecastPointCollection -> [ProcessedWeatherPoint]
adjustTemp Nothing = []
adjustTemp (Just (ForecastPointCollection points)) = processWeatherPoint <$> points
adjustTemp :: Maybe ForecastPointCollection -> [ProcessedWeatherPoint]
adjustTemp Nothing = []
adjustTemp (Just forecast) = processWeatherPoint <$> forecastpointcollection forecast
adjustTemp :: Maybe ForecastPointCollection -> [ProcessedWeatherPoint]
adjustTemp = maybe [] (fmap processWeatherPoint . forecastpointcollection)