Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override show method for String/Char in Haskell

I have a question: How can I override the show method for String or Char ? Thanks.

like image 749
Academia Avatar asked Nov 19 '11 05:11

Academia


2 Answers

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 Chars with MyChar, like so:

print $ fmap MyChar "test"

This will print out

[head "t",head "e",head "s",head "t"]
like image 53
Lily Ballard Avatar answered Nov 07 '22 20:11

Lily Ballard


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

like image 2
ivanm Avatar answered Nov 07 '22 21:11

ivanm