| 1 | 11c11,26 |
|---|
| 2 | < -- The 'trace' function. |
|---|
| 3 | --- |
|---|
| 4 | > -- The 'trace' function is intended for printing debug messages. |
|---|
| 5 | > -- Using 'trace', a message is printed as a side effect of evaluating an expression. |
|---|
| 6 | > -- |
|---|
| 7 | > -- Example: |
|---|
| 8 | > -- |
|---|
| 9 | > -- > fib 0 = trace "base 0" 1 |
|---|
| 10 | > -- > fib 1 = trace "base 1" 1 |
|---|
| 11 | > -- > fib n = trace ("fib " ++ show n) (fib (n-1) + fib (n-2)) |
|---|
| 12 | > -- |
|---|
| 13 | > -- Now calculating @fib 3@ will output: |
|---|
| 14 | > -- |
|---|
| 15 | > -- > fib 3 |
|---|
| 16 | > -- > fib 2 |
|---|
| 17 | > -- > base 1 |
|---|
| 18 | > -- > base 0 |
|---|
| 19 | > -- > base 1 |
|---|
| 20 | 16d30 |
|---|
| 21 | < -- * Tracing |
|---|
| 22 | 19c33,36 |
|---|
| 23 | < traceShow |
|---|
| 24 | --- |
|---|
| 25 | > traceShow, |
|---|
| 26 | > withTrace, |
|---|
| 27 | > traceM, |
|---|
| 28 | > traceShowM |
|---|
| 29 | 70a88,107 |
|---|
| 30 | > |
|---|
| 31 | > -- | The expression @withTrace msg x@ prints @msg ++ show x@ before returning @x@. |
|---|
| 32 | > withTrace :: Show a => String -> a -> a |
|---|
| 33 | > withTrace msg x = trace (msg ++ show x) x |
|---|
| 34 | > |
|---|
| 35 | > -- | Output the specified string before returning @()@. This function is intended for tracing in a do-block. |
|---|
| 36 | > -- |
|---|
| 37 | > -- Note: In non-strict monads you need to write |
|---|
| 38 | > -- |
|---|
| 39 | > -- > do () <- traceM msg |
|---|
| 40 | > -- |
|---|
| 41 | > -- to ensure that the trace message is output. |
|---|
| 42 | > traceM :: Monad m => String -> m () |
|---|
| 43 | > traceM msg = trace msg (return ()) |
|---|
| 44 | > |
|---|
| 45 | > -- | Like 'traceM', but uses 'show' on the argument to convert it to a 'String'. |
|---|
| 46 | > -- |
|---|
| 47 | > -- > traceShowM = traceM . show |
|---|
| 48 | > traceShowM :: (Show a, Monad m) => a -> m () |
|---|
| 49 | > traceShowM = traceM . show |
|---|