我正在尝试使用show函数并返回类似于JSON的输出,我必须使用的类型是
data JSON = JNum Double
| JStr String我在找
JNum 12,JStr"bye",JNum 9,JStr"hi“返回
[12, "bye", 9, "hi"]我尝试过:
instance Show JSON where
show ans = "[" ++ ans ++ "]"但由于编译错误而失败。我也试过
instance Show JSON where
show ans = "[" ++ ans ++ intercalate ", " ++ "]"但是失败了,因为“不在作用域中:数据构造器' JSON‘不确定如何使用"ans”来表示JSON在输出中接收的任何类型,不管是字符串还是double..etc……不太适合Haskell,所以任何提示都会很好。“
Thx用于阅读
发布于 2015-02-01 02:08:18
通过将deriving (Show)添加到数据声明中,您可以让GHC自动为您派生一个show函数,例如:
data JSON = ... deriving (Show)至于您的代码,为了让show ans = "[" ++ ans ++ "]"输入check,ans需要是一个字符串,但是ans的类型是JSON。
要编写您自己的show函数,您必须编写如下代码:
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数字的任何方式。
发布于 2015-02-01 02:09:34
如果您想编写自己的实例,可以这样做:
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定义的实例。
演示:
λ> JArr[JNum 12, JStr"bye", JNum 9, JStr"hi"]
[12.0,bye,9.0,hi]https://stackoverflow.com/questions/28254680
复制相似问题