How to debug Haskell code?

Viewed 20671

I have a problem. I wrote a big Haskell program, and it always works with small input. Now, when I want to test it and generate a bigger input, I always get the message:

HsProg: Prelude.head: empty list

I use Prelude.head many times. What can I do to find out more or get a better error output to get the code line in which it happens?

4 Answers

Since GHC 8, you can use the GHC.Stack module or some profiling compiler flags detailed on a Simon's blog.

You can use this library: Debug.Trace

You can replace any value a with the function:

trace :: String -> a -> a

unlike putStrLn there is no IO in the output, e.g.:

>>> let x = 123; f = show
>>> trace ("calling f with x = " ++ show x) (f x)
calling f with x = 123
123

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.

Related