Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`show` record without deriving Show

Tags:

haskell

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?

like image 439
Qwertie Avatar asked Jun 11 '26 00:06

Qwertie


1 Answers

Standalone deriving

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}

Generics

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}

GHCi :force

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.

like image 65
Chris Martin Avatar answered Jun 14 '26 07:06

Chris Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!