我正在使用的类型
data J = JObj[(String, J)]
| JArr[J]
| JStr String当给定输入时:
JObj[("problem", "solving")]我希望输出为:
{"problem":"solving"}但是因为JStr是一个列表,所以它一直输出{["problem", "solving"]},这是上面指定的JStr的方式,但不是我想要的。
这就是我所拥有的:
show(JStr x) = show x
show(JObj x) = "{" ++ show (foldl (x)) ++ "}"
show(JArr x) = show x我相信我可以使用map/ fold (我的实现是错误的吗?)在列表上,但我不知道如何继续下去。我还考虑在Data.List中使用intercalate & intersperse来实现这一点。Thnks
发布于 2015-02-01 05:07:48
考虑一下手头的语法。对于JObj列表中的任何一对(String, J),我们最终都希望看到(s, j)成为"s": j
jpair :: (String, J) -> String
jpair (s, j) = show s ++ " : " ++ show j现在,如果我们有一个列表[(String, J)],那么我们可以产生一个"s": j字符串片段的列表,但我们需要通过散布逗号来组合它们,而不是滥用Haskell list语法,它将包括[和]括号。
此功能在Data.List.intersperse中可用
intersperse :: a -> [a] -> [a]或者,更好的是,在Data.List.intercalate中
intercalate :: [a] -> [[a]] -> [a]
intercalate med = concat . intersperse med我们可以使用intercalate得到我们想要的东西
instance Show J where
show(JStr x) = show x
show(JObj x) = "{" ++ intercalate "," (map jpair x) ++ "}"
show(JArr x) = show xhttps://stackoverflow.com/questions/28256326
复制相似问题