[Haskell-cafe] x -> String

Jochem Berndsen jochem at functor.nl
Fri Oct 16 14:29:07 EDT 2009

Andrew Coppin wrote:
> Is there any way that you can turn an arbitrary Haskell value into a
> string?

No, the only values of type
a -> String
are the constant functions and _|_.

> I rephrase: There *is* a way to turn arbitrary values into strings. I
> know there is, because the GHCi debugger *does* it. The question is,
> does anybody know of an /easy/ way to do this?

No. GHCi does not always do this:

Prelude Data.Ratio> let plus1 = (+1)
Prelude Data.Ratio> plus1

    No instance for (Show (a -> a))
      arising from a use of `print' at <interactive>:1:0-4
    Possible fix: add an instance declaration for (Show (a -> a))
    In a stmt of a 'do' expression: print it
Prelude Data.Ratio>

> Basically, I'm writing a mutable container implementation. It can hold
> any type of data, but it would massively aid debugging if I could
> actually print out what's in it. On the other hand, I don't want to
> alter the entire program to have Show constraints everywhere just so I
> can print out some debug traces (and then alter everything back again
> afterwards once I'm done debugging).

This is not advisable, as you see.

> Anybody know of a way to do this? (As it happens, the values I'm testing
> with are all Showable anyway, but the type checker doesn't know that...)

What is the problem with adding a function
showMyContainer :: (Show a) => Container a -> String
In this case you can show your container (for debugging purposes), but
only if you have Showable elements in your container.

Cheers, Jochem

Jochem Berndsen | jochem at functor.nl | jochem@牛在田里.com

More information about the Haskell-Cafe mailing list