Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: any debugShow function?

I want to use Debug.Trace.trace to print something which I know is a Show. Just like I would do in Python etc.

One solution is to add "Show a =>" to the signature of the function where I want to put the trace, and to any function calling it, etc.

But it would had been much nicer if I could use some debugShow function which calls show if the value has one, otherwise returns "--no show--" or something.

Here's my failed attempt to define a DebugShow (GHC rejects "Duplicate instance declarations"):

{-# LANGUAGE FlexibleInstances, UndecidableInstances, OverlappingInstances #-}

class DebugShow a where
  debugShow :: a -> String

instance Show a => DebugShow a where
  debugShow = show

instance DebugShow a where
  debugShow = const "--no show--"

Some kind of "unsafe cast" would also solve my problem.

Any advice?

Note - This is only for debugging purposes. I'm not using this in any finished code.

like image 719
yairchu Avatar asked Feb 28 '23 12:02

yairchu


1 Answers

Perhaps you want some variant of:

traceShow :: (Show a) => a -> b -> b
traceShow = trace . show

defined in Debug.Trace

The constraint "calls show if the value has one, otherwise returns "--no show--" or something" is a hard one. You'll need overlapping (and incoherent) instances, I think, to define a default Show for all types (Perhaps via unsafeCoerce, or via vacuum).

like image 128
Don Stewart Avatar answered Mar 06 '23 21:03

Don Stewart