Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple debugging in Haskell

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.

like image 955
Jackson Cotwannaie Avatar asked Aug 31 '11 06:08

Jackson Cotwannaie


People also ask

How do I debug a Haskell program?

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.

Is there a Haskell debugger?

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.

What does debug trace do?

Debug. Trace. Functions for tracing and monitoring execution. These can be useful for investigating bugs or performance problems.


1 Answers

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.

like image 97
Adam Burke Avatar answered Sep 20 '22 02:09

Adam Burke