Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Haskell的JSON输出_Json_Haskell - Fatal编程技术网

使用Haskell的JSON输出

使用Haskell的JSON输出,json,haskell,Json,Haskell,我正在尝试使用show函数并返回类似于JSON的输出 我必须与之合作的类型是 data JSON = JNum Double | JStr String 我在找 JNum 12,JStr“再见”,JNum 9,JStr“嗨” 归来 [12, "bye", 9, "hi"] 我曾尝试: instance Show JSON where show ans = "[" ++ ans ++ "]" 但由于编译错误而失败。 我也试过了 instance Show JSON w

我正在尝试使用show函数并返回类似于JSON的输出 我必须与之合作的类型是

data JSON = JNum Double
          | JStr String
我在找

JNum 12,JStr“再见”,JNum 9,JStr“嗨” 归来

[12, "bye", 9, "hi"]
我曾尝试:

instance Show JSON where
  show ans = "[" ++ ans ++ "]"
但由于编译错误而失败。 我也试过了

instance Show JSON where
  show ans = "[" ++ ans ++ intercalate ", " ++ "]"
但因“不在范围内:数据构造函数'JSON'而失败” 不知道如何使用“ans”来表示JSON在输出中作为输入接收的任何类型,可以是字符串、双精度..等等。。。 对Haskell不是很好,所以任何提示都很好


Thx对于读取

您可以让GHC通过在数据声明中添加导出(显示)来自动为您导出一个显示函数,例如:

data JSON = ... deriving (Show)
至于您的代码,为了让
show ans=“[”++ans++“]”“
键入check
ans
需要是一个字符串,但是
ans
具有类型JSON

要编写自己的show function,您必须编写以下内容:

instance Show JSON where
   show (JNum d) = ... code for the JNum constructor ...
   show (JObj pairs) = ... code for the JObj constructor ...
   show (JArr arr) = ... code for the JArr constructor ...
   ...
此处
d
的类型为Double,因此对于第一种情况,您可以编写:

   show (JNum d) = "JNum " ++ show d

或者,您希望以何种方式表示JSON编号。

如果您希望编写自己的实例,可以执行以下操作:

instance Show JSON where
  show (JNum x) = show x
  show (JStr x) = x
  show (JObj xs) = show xs
  show (JArr xs) = show xs
请注意,对于
JObj
JArr
数据构造函数,节目将使用为
JObj
JArr
定义的实例

演示:


你为什么写“show(jstrx)=x”而不是“show(jstrx)”呢=显示x'?谢谢you@SumYungGai它们都是等价的。
show x
将生成
String
,但对于
JStr s
数据构造函数,
s
已经是
String
@Sibi实际上,它们并不等价:如果
s
是字符串,
show s
将在
s
和e>周围添加引号替换
s
中的任何引号以及任何其他“特殊”字符。@chi谢谢,我不知道!
λ> JArr[JNum 12, JStr"bye", JNum 9, JStr"hi"] 
[12.0,bye,9.0,hi]