Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trace output in pure function

Tags:

haskell

ghc

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?

like image 850
Cartesius00 Avatar asked Dec 08 '22 19:12

Cartesius00


2 Answers

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.

like image 168
hammar Avatar answered Jan 04 '23 03:01

hammar


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
like image 26
leftaroundabout Avatar answered Jan 04 '23 03:01

leftaroundabout