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?

1

2 Answers 2

23

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"
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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
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
20

Use Debug.Trace.trace.

import Debug.Trace

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.