I am new to Haskell. Previously I have programmed in Python and Java. When I am debugging some code I have a habit of littering it with print
statements in the middle of code. However doing so in Haskell will change semantics, and I will have to change my function signatures to those with IO
stuff. How do Haskellers deal with this? I might be missing something obvious. Please enlighten.
Debugging. To debug the main function of a file, press cmd-shift-p (Mac) or ctrl-shift-p (Linux/Windows) to launch the command palette, type in haskell debug and press enter.
Hoed - The Lightweight Haskell Tracer and Debugger Hoed is a tracer/debugger that offers most of HATs functionality, and works with untransformed libraries. Hoed can therefore be used to debug much more programs than traditional tracer/debuggers.
Debug. Trace. Functions for tracing and monitoring execution. These can be useful for investigating bugs or performance problems.
Other answers link the official doco and the Haskell wiki but if you've made it to this answer let's assume you bounced off those for whatever reason. The wikibook also has an example using Fibonacci which I found more accessible. This is a deliberately basic example which might hopefully help.
Let's say we start with this very simple function, which for important business reasons, adds "bob" to a string, then reverses it.
bobreverse x = reverse ("bob" ++ x)
Output in GHCI:
> bobreverse "jill"
"llijbob"
We don't see how this could possibly be going wrong, but something near it is, so we add debug.
import Debug.Trace
bobreverse x = trace ("DEBUG: bobreverse" ++ show x) (reverse ("bob" ++ x))
Output:
> bobreverse "jill"
"DEBUG: bobreverse "jill"
llijbob"
We are using show
just to ensure x
is converted to a string correctly before output. We also added some parenthesis to make sure the arguments were grouped correctly.
In summary, the trace
function is a decorator which prints the first argument and returns the second. It looks like a pure function, so you don't need to bring IO
or other signatures into the functions to use it. It does this by cheating, which is explained further in the linked documentation above, if you are curious.
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