gpt4 book ai didi

haskell - 如何为具有多个不带参数的构造函数的代数数据类型创建 ToJSON/FromJSON 条目?

转载 作者:行者123 更新时间:2023-12-02 00:55:11 25 4
gpt4 key购买 nike

鉴于此数据:

data A1 = A1 | A2 | A3

如何为其创建实例?

instance ToJSON A1 where
toJSON = ???

instance FromJSON A1 where
parseJSON = ???

如果它是单个构造函数,我可以做到这一点,但我无法弄清楚如何使用多个不接受任何参数的构造函数来做到这一点。

更新:对于每个构造函数,我都有这些错误:

my-app/src/Lib.hs:54:32:
No instance for (ToJSON a1) arising from a use of ‘.=’
The type variable ‘a1’ is ambiguous
Note: there are several potential instances:
instance ToJSON UUID -- Defined in ‘Data.UUID.Aeson’
instance ToJSON MyType -- Defined at src/Lib.hs:53:10
instance ToJSON MyType2 -- Defined at src/Lib.hs:70:10
In the expression: "tag" .= "A1"
In the first argument of ‘object’, namely ‘["tag" .= "A1"]’
In the expression: object ["tag" .= "A1"]

my-app/src/Lib.hs:54:35:
No instance for (Data.String.IsString a1)
arising from the literal ‘"A1"’
The type variable ‘a1’ is ambiguous
Note: there are several potential instances:
instance Data.String.IsString Value
-- Defined in ‘aeson-0.9.0.1:Data.Aeson.Types.Internal’
instance (a
~ bytestring-0.10.6.0:Data.ByteString.Internal.ByteString) =>
Data.String.IsString
(attoparsec-0.13.0.1:Data.Attoparsec.ByteString.Internal.Parser a)
-- Defined in ‘attoparsec-0.13.0.1:Data.Attoparsec.ByteString.Char8’
instance Data.String.IsString
bytestring-0.10.6.0:Data.ByteString.Builder.Internal.Builder
-- Defined in ‘bytestring-0.10.6.0:Data.ByteString.Builder’
...plus 13 others
In the second argument of ‘(.=)’, namely ‘"A1"’
In the expression: "tag" .= "A1"
In the first argument of ‘object’, namely ‘["tag" .= "A1"]’

最佳答案

编辑中显示的问题都是关于类型歧义的,可以通过使用函数应用程序使类型可推断或添加类型注释来解决。

  • .= 的右侧是字符串文字,因此可以是 StringText 或其他 - 用 注释::Text 或像我下面那样做并使用 Text.pack 。显示
  • .: 的结果是多态的,大小写模式都是导致同样问题的字符串文字。在下面,我将 ::Text 添加到 tag 中,从而消除了歧义。

完整代码:

{-# LANGUAGE OverloadedStrings #-}

import Data.Aeson
import Data.Aeson.Types
import Control.Monad
import Data.Text as Text

data A1 = A1 | A2 | A3
deriving (Eq, Ord, Show)


instance ToJSON A1 where
toJSON a = object ["tag" .= Text.pack (show a)]

instance FromJSON A1 where
parseJSON (Object o) = do
tag <- o .: "tag"
case (tag :: Text) of
"A1" -> return A1
"A2" -> return A2
"A3" -> return A3
_ -> mzero
parseJSON v = typeMismatch "A1" v

关于haskell - 如何为具有多个不带参数的构造函数的代数数据类型创建 ToJSON/FromJSON 条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36203139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com