Cartesius00
Cartesius00

Reputation: 24414

Trace output in pure function

Is it somehow possible to print a trace log in the pure function like:

pure :: Int -> Int
pure x = do
  <trace log>
  return x*x

I know, it's not "Haskell clean" but isn't there any useful hack in GHC?

Upvotes: 4

Views: 792

Answers (2)

hammar
hammar

Reputation: 139930

For debugging, you can use the Debug.Trace module.

import Debug.Trace

pure :: Int -> Int
pure x = trace "log" (x * x)

Note that due to laziness the output can in some cases get intermingled with other output you're generating, so this is not recommended for logging in production code, but for simple debugging tasks it's usually fine.

Upvotes: 13

leftaroundabout
leftaroundabout

Reputation: 120751

Of course, there's always unsafePerformIO. Not that it would be a good idea to use it here!

import System.IO.Unsafe

pure :: Int -> Int
pure x = unsafePerformIO $ do
  print x
  return $ x*x

Upvotes: 1

Related Questions