1

Here is my datatype:

data Foo a =  Value Integer
           |Boo a

and I have a function for converting the Foo datatype to String:

showFoo::Show a=> Foo a -> String
showFoo (Value n) = show n
showFoo (Boo a) = show a

For example: showFoo (Value 10) becomes: "10", but for showFoo(Boo "S"), it becomes: "\"S\"" but I need only "S".

2 Answers 2

4

This boils down to the behaviour of show with strings. show is designed to give machine-readable output, it's not a pretty-printer, so it puts inverted commas round all strings. That way it can tell the difference between 10 and "10" when it's reading them back in.

Your showFoo function is clearly not designed to be in the show family, since it obliterates the Value and Boo tags, so using show isn't really what you mean.

Possible solutions:

  1. Give in, go the whole hog and derive Show.
  2. If a is always a String, change your data type and don't use show.
  3. Learn about type classes some more and define your own Showish class. Use -XFlexibleInstances and -XOverlappingInstances to override the instance for String, and don't use quotes.
  4. Hack it by using init.tail.show $ a
Sign up to request clarification or add additional context in comments.

Comments

1

That's just a result of you using GHCi and it showing the previous result. Try this in a compiled program or try running (in GHCi) putStrLn (showFoo (Boo "S")) and you will see that calling show on a string results in a single set of quotes.

3 Comments

I understand your point, but I can not change signature of the function (putStrLn can't be used).
I sympathize with you, but I can't (or am not motivated to) help when there are artificial constraints. I suppose you could do something like filter (/='"') (show a) (or just conditionally drop " if they are the first and last characters).
I'm pretty sure the fundamental problem is that the OP wants show "foo" to result in "foo". I don't think not wanting to put a function Foo a -> String` into the IO monad and always write to console is an "artificial constraint" on the solution.

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.