11

I am new to Haskell and I'm wondering if there's a way to output 'debug' lines within a function in Haskell? I.E. I want to debug what values are being inputted into a function

My current code is

import Prelude

foo(a,b,c) 
    print("input a : " ++ a)
    = a + b + c

main = print(foo(1, 2, 3))

I have experience with programming, but this is my first time going near functional programming, so any help will be appreciated.

hammar
  • 138,522
  • 17
  • 304
  • 385
AlanFoster
  • 8,156
  • 5
  • 35
  • 52

2 Answers2

21

You're looking for Debug.Trace.trace.

import Debug.Trace
foo a b c = trace ("input a: " ++ show a) (a + b + c)
main = print (foo 1 2 3)

trace is a function that prints its first argument before returning its second. However, it's not referentially transparent, so it should only be used for debugging.

Also, note that parentheses are not used for function application in Haskell, only for grouping.

hammar
  • 138,522
  • 17
  • 304
  • 385
  • @user551841, `show` produces a string representation of a value (for printing and such). – Adam Wagner Dec 04 '11 at 04:25
  • 13
    @user551841: Don't Google, [Hoogle](http://www.haskell.org/hoogle/?hoogle=show)! It's a specialized search engine for Haskell documentation, and it has the rather unique feature of being able to search for functions _by type_. If you're getting into Haskell, you might as well get aquainted with it. – hammar Dec 04 '11 at 04:26
  • Note that if this is anything like "debug trace" functionality I've encountered in other enforced-purity languages, you may sometimes surprise yourself, particularly with optimizations enabled. The compiler probably ensures the traces aren't optimised out of function you put them in, but they won't impact the purity of those functions themselves. So they can still be re-ordered or optimized away entirely if the compiler sees fit. And in a lazy language like Haskell, the order in which things are actually executed may not be at all intuitive to you. – Ben Dec 05 '11 at 02:11
  • http://learnyouahaskell.com/input-and-output also fails to tell new users how to actually print something outside of main. Sorry, if this sounds obnoxious but keeping people stupid does not help making haskell popular. Any time someone is trying to do some continuation style programming they WILL run into that exact problem. (Example: GUI framework). – BitTickler Aug 12 '15 at 03:12
9

In addition to @hammar's suggestion of trace, you could use traceShow (also from Debug.Trace, and simply defined)

import Debug.Trace (traceShow)
foo a b c = traceShow (a, b, c) (a + b + c)
main = print (foo 1 2 3)
Adam Wagner
  • 15,469
  • 7
  • 52
  • 66