Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Print Lines in function

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.

like image 544
AlanFoster Avatar asked Dec 04 '11 04:12

AlanFoster


People also ask

How do I print a list of elements in Haskell?

If show is ok to print your elements, you can use putStr ( unlines $ map show [(1,"A"),(2,"B"),(3,"C"),(4,"D")]) but you can replace show by any funtion that'll take your custom type and return a string.

How do you read a string in Haskell?

In Haskell read function is used to deal with strings, if you want to parse any string to any particular type than we can use read function from the Haskell programming. In Haskell read function is the in built function, that means we do not require to include or install any dependency for it, we can use it directly.

What is returns Haskell?

return is actually just a simple function in Haskell. It does not return something. It wraps a value into a monad. Looks like return is an overloaded function.


2 Answers

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.

like image 79
hammar Avatar answered Oct 04 '22 02:10

hammar


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)
like image 21
Adam Wagner Avatar answered Oct 04 '22 03:10

Adam Wagner