Haskell CS 421 LogoCS 421 — Programming Languages

Using Debug.Trace

In “normal” languages you can just put in some printf statements to help you figure out what’s going on in your program. It turns out you can do that in Haskell too.

There is a package called Debug.Trace that provides, among other things, a handy function trace :: String -> a -> a that prints out the given string and then returns the value. This is particularly useful with ghci.

Here’s an example seesion.

% stack ghci
GHCi, version 8.6.3: http://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from /tmp/haskell-stack-ghci/2a3bbd58/ghci-script
Prelude> import Debug.Trace
Prelude Debug.Trace> :{
Prelude Debug.Trace| fact 0 = trace "Base case." 1
Prelude Debug.Trace| fact n = trace ("Recursive case " ++ show n) $ n * fact (n-1)
Prelude Debug.Trace| :}
Prelude Debug.Trace> fact 6
Recursive case 6
Recursive case 5
Recursive case 4
Recursive case 3
Recursive case 2
Recursive case 1
Base case.
720

For more information, see the Debug.Trace hackage page. There are other functions there you might find helpful as well!