6

How can I print a list or something in haskell at every call for example :

funct a list = funct (a + 1) (a : list) 
               print list here ??????? but how ? 
exilonX
  • 1,712
  • 3
  • 26
  • 50

2 Answers2

11

For debugging, there's

import Debug.Trace

funct :: Integer -> [Integer] -> Bool 
funct a list = trace (show list) $ funct (a + 1) (a : list)

where trace :: String -> a -> a. It uses unsafePerformIO under the hood, so it's evil and only for debugging.

Be aware that due to lazy evaluation, the debugging output may appear in surprising order and interleaved with the output the program would normally generate.

With

module TraceIt where

import Debug.Trace

funct :: Integer -> [Integer] -> Bool
funct 10 list = null list
funct a list = trace (show list) $ funct (a + 1) (a : list)

I get

*TraceIt> funct 1 []
[]
[1]
[2,1]
[3,2,1]
[4,3,2,1]
[5,4,3,2,1]
[6,5,4,3,2,1]
[7,6,5,4,3,2,1]
[8,7,6,5,4,3,2,1]
False

as expected.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • but it works only for the last call, if I go recursively and it enters in a guard it shows only the last call how can I make to show all calls ??? – exilonX Apr 21 '12 at 22:47
  • That would be very surprising. Unless your tracing string is constant and you compile with optimisations, then that is normal. For the above, I get tracing output in every call. – Daniel Fischer Apr 21 '12 at 22:52
  • Ah thanks, forgot about that. It's too new to have reached my long-term memory. – Daniel Fischer Apr 21 '12 at 23:32
1

Same as Daniel Fisher suggested, but with unsafePerformIO only.

> import System.IO.Unsafe
> let funct a list = unsafePerformIO $ do { print list; return $ funct (a + 1) (a : list) }

Take a look at the similar question describes what is really going on when you use unsafePerformIO.

Community
  • 1
  • 1