I’d like to define a function which can “show” values of any type, with special behavior for types which actually do define a Show instance:
magicShowCast :: ?
debugShow :: a -> String
debugShow x = case magicShowCast x of
Just x' -> show x'
Nothing -> "<unprintable>"
This would be used to add more detailed information to error messages when something goes wrong:
-- needs to work on non-Showable types
assertEq :: Eq a => a -> a -> IO ()
assertEq x y = when (x /= y)
(throwIO (AssertionFailed (debugShow x) (debugShow y)))
data CanShow = CanShow1
| CanShow 2
deriving (Eq, Show)
data NoShow = NoShow1
| NoShow2
deriving (Eq)
-- AssertionFailed "CanShow1" "CanShow2"
assertEq CanShow1 CanShow2
-- AssertionFailed "<unprintable>" "<unprintable>"
assertEq NoShow1 NoShow2
Is there any way to do this? I tried using various combinations of GADTs, existential types, and template haskell, but either these aren’t enough or I can’t figure out how to apply them properly.
The real answer: You can’t. Haskell intentionally doesn’t define a generic “serialize to string” function, and being able to do so without some type class constraint would violate parametricity all over town. Dreadful, just dreadful.
If you don’t see why this poses a problem, consider the following type signature:
How would you implement this function? The generic type means it has to be either
const . fstorconst . snd, right? Hmm.Oooooooops! So much for being able to reason about your program in any sane way. That’s it,
show‘s over, go home, it was fun while it lasted.The terrible, no good, unwise answer: Sure, if you don’t mind shamelessly cheating. Did I mention that example above was an actual GHCi session? Ha, ha.
Oh. Ok. That looks like a fantastic idea, doesn’t it.
Anyway, this doesn’t quite give you what you want, since there’s no obvious way to fall back to a proper
Showinstance when available. On the other hand, this lets you do a lot more thanshowcan do, so perhaps it’s a wash.Seriously, though. Don’t do this in actual, working code. Ok, error reporting, debugging, logging… that makes sense. But otherwise, it’s probably very ill-advised.