I have a question: How can I override the show method for String or Char ? Thanks.
Since people seem to like my comment, here it is as an answer:
If you want to reimplement type classes on existing types, you can wrap them in a newtype
-declared type. This allows you to define your own implementations, without any actual overhead at runtime (because newtype
is isomorphic to the original type, there's no actual boxing done at runtime).
This might look something like this:
newtype MyChar = MyChar Char
instance Show MyChar where
show (MyChar c) = "head \"" ++ c : "\""
You can use this by wrapping Char
s with MyChar
, like so:
print $ fmap MyChar "test"
This will print out
[head "t",head "e",head "s",head "t"]
If you're wanting to do this, then you're doing it wrong.
For a more technical reason why, see my answer to a previous question.
You really should be using either your own a -> String
functions (possibly via your own type-class) or use a pretty-printing library for more detailed outputs (some of which already have an inbuilt Pretty
class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With