Reputation: 41
I'm working with the type
data J = JObj[(String, J)]
| JArr[J]
| JStr String
When given the input :
JObj[("problem", "solving")]
I would like the output to be:
{"problem":"solving"}
But since JStr is a list, it keeps printing out {["problem", "solving"]}
which is the way JStr was specified up above, but not what I want.
Here is what I have:
show(JStr x) = show x
show(JObj x) = "{" ++ show (foldl (x)) ++ "}"
show(JArr x) = show x
I believe I can use map/ fold (is my implementation wrong?) on the list but I'm confused as to how to proceed further. I also thought of using intercalate & intersperse within Data.List to approach this. Thnks
Upvotes: 1
Views: 50
Reputation: 74354
Consider the syntax at hand. For any pair (String, J)
inside of the JObj
list we'd like to eventually see (s, j)
become "s": j
jpair :: (String, J) -> String
jpair (s, j) = show s ++ " : " ++ show j
Now, if we have a list [(String, J)]
then we can produce a list of "s": j
string fragments, but we need to combine them by interspersing commas instead of abusing the Haskell list syntax which would include the [
and ]
brackets.
This functionality is available in Data.List.intersperse
intersperse :: a -> [a] -> [a]
or, even better, in Data.List.intercalate
intercalate :: [a] -> [[a]] -> [a]
intercalate med = concat . intersperse med
and we can use intercalate
to get what we want
instance Show J where
show(JStr x) = show x
show(JObj x) = "{" ++ intercalate "," (map jpair x) ++ "}"
show(JArr x) = show x
Upvotes: 2