October 08, 2007

Tracing your code... the dirty way!

Problem: you want to trace your Haskell program but you're scared that touching anything might thrash your type hackery.

Solution: Use Debug.Trace.trace wherever you want to print something on the console:

Before: map f (x:xs) = (f x):(map f xs)
After: map f (x:xs) = trace "Here I am" $ (f x):(map f xs)

Explanation: I was trying to understand how HAppS worked and I really missed the possibility to put a harmless print statemente here and there in the code just to get the feeling of what was happening in the behinds, as I'd do in an imperative language like python.

The problem is that we have to deal with Haskell purity so if you want to print something in a Haskell program, you have to do it inside the IO Monad.

So far so good, but IO is not available everytime you need it... at least not the "official" one. In fact Haskell allows you to enter the IO Monad anytime you need it and perform an IO action straight away using the unsafePerformIO function.

"Unsafe" means that you use it at your own risk, since you're doing something impure in a pure environment. Of course, trace has nothing to do with the real meaning of the traced funcion, so it's perfectly safe to use it that way.

I spent almost an hour to figure out how to do this, so I hope this trick will save you time.