10

I want to debug my program by printing something

For example,

isPos n 
    | n<0       = False
    | otherwise = True

I want something like:

isPos n 
    | n<0       = False AND print ("negative")
    | otherwise = True  AND print ("positive")

Is it possible to do in Haskell?

Ben Millwood
  • 6,754
  • 24
  • 45
JDL Wahaha
  • 695
  • 1
  • 14
  • 22
  • Read before http://www.haskell.org/haskellwiki/Debugging Read after http://stackoverflow.com/questions/672979/what-is-a-good-way-to-debug-haskell-code?rq=1 – Jonke Sep 24 '12 at 06:07

2 Answers2

22

As hammar said, use trace from the Debug.Trace module. A tip I have found useful is to define the function debug:

debug = flip trace

You could then do

isPos n
  | n < 0     = False `debug` "negative"
  | otherwise = True  `debug` "positive"

The benefit of this is that it is easy to enable/disable the debug printing during development. To remove the debug printing, simply comment out rest of the line:

isPos n
  | n < 0     = False -- `debug` "negative"
  | otherwise = True  -- `debug` "positive"
beta
  • 2,380
  • 21
  • 38
  • 9
    I've often also found the variation `debug = (flip trace) False` useful. If I have a guards-based function definition, I simply insert a (or multiple) `| debug ("Interesting value is " ++ show whatever) = undefined` as the first guard(s). The trace is always run, but since `debug x` is always `False`, the guard always fails and the program behaves as normal. This makes it easy to quickly inspect values, at least in functions that already have guards. – gspr Sep 23 '12 at 14:31
  • You can also have the following two definitions at the top of your file, and simply toggle between them to toggle debug mode: `debug = flip trace` and `debug a b = a` – Achal Dave Jul 08 '13 at 00:25
  • 1
    Apparently I can't edit that comment anymore; a simpler way is to have a `doDebug` boolean and define `debug` as `debug a b = if doDebug then trace b a else a` – Achal Dave Jul 08 '13 at 00:31
19

Use Debug.Trace.trace.

import Debug.Trace

isPos n 
  | n < 0     = trace "negative" False
  | otherwise = trace "positive" True 
hammar
  • 138,522
  • 17
  • 304
  • 385