Haskell/Debugging

Debug prints with
Debug prints are a common way to debug programs. In imperative languages, we can just sprinkle the code with print statements to standard output or to some as log file in order to track debug information (e.g. value of a particular variable, or some human-readable message). In Haskell, however, we cannot output any information other than through the IO monad; and we don't want to introduce that just for debugging.

To deal with this problem, the standard library provides the. That module exports a function called  which provides a convenient way to attach debug print statements anywhere in a program. For instance, this program prints every argument passed to  when not equal to 0 or 1:

Below is the resulting output:

n: 4 n: 3 n: 2 n: 2 fib 4: 3

Also,  makes it possible to trace execution steps of program; that is, which function is called first, second, etc. To do so, we annotate parts of functions we are interested in, like this:

When a program annotated in such way is run, it will print the debug strings in the same order the annotated statements were executed. That output might help to locate errors in case of missing statements or similar things.

Some extra advice
As demonstrated above,  can be used outside of the IO monad; and indeed its type signature...

...indicates that it is a pure function. Yet surely  is doing IO while printing useful messages. What's going on? In fact,  uses a dirty trick of sorts to circumvent the separation between IO and pure Haskell. That is reflected in the following disclaimer, found in the documentation for: The trace function should only be used for debugging, or for monitoring execution. The function is not referentially transparent: its type indicates that it is a pure function but it has the side effect of outputting the trace message.

A common mistake in using : while trying to fit the debug traces into an existing function, one accidentally includes the value being evaluated in the message to be printed by  ; e.g. don't do anything like this:

That leads to infinite recursion because trace message will be evaluated before bar expression which will lead to evaluation of foo in terms of trace message and bar again and trace message will be evaluated before bar and so forth to infinity. Instead of, the correct trace message should have  :

Useful idioms
A helper function that incorporates  can be convenient:

In a similar vein,  defines a   function, that "prints" its first argument and evaluates to the second one:

Finally, a function  like this one may prove handy as well:

This will allow you to write code like...

... making it easier to comment/uncomment debugging statements.