2

I am trying to use the show function and get back output that looks like JSON The type I have to work with is

data JSON = JNum Double
          | JStr String

I am looking for

JNum 12, JStr"bye", JNum 9, JStr"hi" to return

[12, "bye", 9, "hi"]

I have attempted:

instance Show JSON where
  show ans = "[" ++ ans ++ "]"

but fails with a compile error. I have also tried

instance Show JSON where
  show ans = "[" ++ ans ++ intercalate ", " ++ "]"

but failed with "Not in scope: data constructor 'JSON' Not sure how to use "ans" to represent whatever type JSON receives as input in the ouput, be it a string, double..etc... Not very good with Haskell so any hints would be great.

Thx for reading

2 Answers 2

2

You can have GHC automatically derive a show function for you by adding deriving (Show) to your data declaration, e.g.:

data JSON = ... deriving (Show)

As for your code, in order for show ans = "[" ++ ans ++ "]" to type check ans needs to be a String, but ans has type JSON.

To write your own show function you have to write something like:

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 ...
   ...

Here d will have type Double, so for the first case you might write:

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

or however you want to represent a JSON number.

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to write your own instance, you can do something like this:

instance Show JSON where
  show (JNum x) = show x
  show (JStr x) = x
  show (JObj xs) = show xs
  show (JArr xs) = show xs

Note that for JObj and JArr data constructor, the show will use the instance defined for JObj and JArr.

Demo:

λ> JArr[JNum 12, JStr"bye", JNum 9, JStr"hi"] 
[12.0,bye,9.0,hi]

3 Comments

How come you wrote 'show (JStr x) = x' rather than 'show (JStr x ) = show x '? Thank you
@SumYungGai They both are equivalent. show x will produce String but for JStr s data constructor, s is already a String
@Sibi Actually, they are not equivalent: if s is a string, show s will add quotes around s, as well as escape any quotes which might be inside s, and any other "special" characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.