Quite often I need to print something while debugging and unless the datatype I need to see derives Show I can't print it. For some datatypes I can't add deriving (Show) to the definition because it may be in a library or somewhere else I can't get to.
Is there anyway I can print these datatypes for debugging?
A deriving clause on the type definition isn't the only way to derive. You can also use the StandaloneDeriving GHC language extension.
λ> :set -XStandaloneDeriving
λ> data Person = Human { name :: String, age :: Int } | Dog { goodPupper :: Bool }
λ> deriving instance Show Person
λ> Human "Chris" 31
Human {name = "Chris", age = 31}
If the type has a Generic instance, you can stringify it with the gshowsPrecdefault function from the generic-deriving package.
λ> import GHC.Generics
λ> import Generics.Deriving.Show
λ> data Person = Human { name :: String, age :: Int } | Dog { goodPupper :: Bool } deriving Generic
λ> putStrLn $ gshowsPrecdefault 0 (Dog True) ""
Dog {goodPupper = True}
You can use the :force command in GHCi to inspect a value.
λ> data Person = Human { name :: String, age :: Int } | Dog { goodPupper :: Bool }
λ> x = Human "Chris" 31
λ> x
<interactive>:17:1: error:
• No instance for (Show Person) arising from a use of ‘print’
• In a stmt of an interactive GHCi command: print it
λ> :force x
x = <Human> "Chris" 31
See Breakpoints and inspecting variables in the GHC manual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With