Hasseell ADT与aeson [英] Haskell ADTs with aeson

查看:148
本文介绍了Hasseell ADT与aeson的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在与一个简单的ADT斗争,试图让它来回往返于JSON,但是我没有运气,不管我如何尝试按摩或修改类型。我错过了什么?



编译时,我总是得到相同的运行时错误:

 >让t =华氏温度
> fromJSON $ toJSON t
错误期待遇到(),遇到Object而不是

尝试这只是给了我没有,大概是因为相同的错误:解码$编码t



我试图遵循这些来源,但我似乎无法解决这个运行时错误,无论我尝试什么:
Haskell :: Aeson ::根据字段值解析ADT
https://www.fpcomplete.com/user/Geraldus/algebraic-data-types-adts-with-aeson



<这是我使用的一种代码形式。起初,我试图将它用作嵌入另一种类型的类型,但是当它不起作用时,我添加了value键来尝试对此进行解析(没有运气)。

  data TemperatureType =摄氏度
|华氏度
导出(Show,Read,Typeable,Data,Eq)

- 这不起作用
- $(deriveJSON defaultOptions''TemperatureType)

实例ToJSON TemperatureType其中
toJSON Fahrenheit = object [value。= StringFahrenheit]
toJSON Celsius = object [value。= StringCelsius]

实例FromJSON TemperatureType其中
parseJSON(Object x)= toTemperatureType< $> x。:value

toTemperatureType :: Text - >温度类型
toTemperatureType华氏度=华氏温度
温度类型摄氏度=摄氏温度


解决方案

Haskell需要关于您的表达式结果类型的帮助,因为在当前调用中无法推断它:

 > fromJSON $ toJSON t :: Result TemperatureType 


I've been fighting with a simple ADT, trying to get it to round-trip back and forth to JSON, but I've had no luck, no matter how I try to massage or modify the type. What am I missing?

When it compiles, I always get the same runtime error:

> let t = Fahrenheit
> fromJSON $ toJSON t
Error "when expecting a (), encountered Object instead"

Trying this just gives me "Nothing", presumably because of the same error: decode $ encode t

I've tried to follow these sources, but I can't seem to get around this runtime error, no matter what I try: Haskell :: Aeson :: parse ADT based on field value https://www.fpcomplete.com/user/Geraldus/algebraic-data-types-adts-with-aeson

Here's one form of the code I'm using. At first, I tried to use this as a type embedded in another type, but when that didn't work I added the "value" key to try to make parsing of this easier (no luck).

data TemperatureType = Celsius
                     | Fahrenheit
                     deriving (Show,Read,Typeable,Data,Eq)

-- This doesn't work either
-- $(deriveJSON defaultOptions ''TemperatureType)

instance ToJSON TemperatureType where
   toJSON Fahrenheit = object [ "value" .= String "Fahrenheit" ]
   toJSON Celsius    = object [ "value" .= String "Celsius" ]

instance FromJSON TemperatureType where
    parseJSON (Object x) = toTemperatureType <$> x .: "value"

toTemperatureType :: Text -> TemperatureType
toTemperatureType "Fahrenheit" = Fahrenheit
toTemperatureType "Celsius"    = Celsius

解决方案

Haskell need help from you about the type of your expression result since in the current call it's not possible to infer it:

> fromJSON $ toJSON t :: Result TemperatureType

这篇关于Hasseell ADT与aeson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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