[Haskell-cafe] fromString and toString

Niklas Hambüchen mail at nh2.me
Wed Feb 5 12:19:24 UTC 2014


On 05/02/14 09:35, Erik Hesselink wrote:
> Show is usually valid Haskell (at least derived instances are), and
> has instances for most types. This class would only be a conversion
> from types that *are* strings in some sense (like Text) to String.

Totally agree.


On 05/02/14 08:13, Atze van der Ploeg wrote:
> Isn't toString just show?

No, show is very different:

   show "hello" == "\"hello\""

While you would expect

   toString "hello" == "hello"


Personally, I would always recommend this:

* Make show represent the "programmer version" of your data type, e.g.
close to what "deriving Show" would give you, and implement it for every
data type:

  newtype MyString = MyS String

  instance Show MyString where
    show (MyS s) = "MyS "  ++ show s

* Use a different type class (e.g. a ToString) to represent the
stringyness of your type:

  instance ToString MyString where
    show (MyS s) = s

>From my experience, everything else makes programming really nasty,
outcomes unpredictable, and debugging very hard.
If you want an example, try GHC code / the GHC API, where many things
unfortunately do not have a show instance.


> We have a (very small) package for this called 'isstring' that we use
> internally. It has instances for String, Text (x2) and ByteString (x2)
> assuming UTF8 encoding. I'd be happy to open source it if people are
> interested.

Yes. And I think a `ToString` typeclass would be useful be in base.

Also, this existed once but is now deprecate it:
http://hackage.haskell.org/package/to-string-class

I speculate that it got deprecated because it is not nice to maintain
all the orphan instances - the class in base would fix that.


More information about the Haskell-Cafe mailing list