Debug Print Status

How can we print the current state value for debugging purposes? For example, in the code from specific example-1 http://www.haskell.org/haskellwiki/State_Monad , how can we print the current state value after reading each input character?

module StateGame where import Control.Monad.State type GameValue = Int type GameState = (Bool, Int) playGame :: String -> State GameState GameValue playGame [] = do (_, score) <- get return score playGame (x:xs) = do (on, score) <- get case x of 'a' | on -> put (on, score + 1) 'b' | on -> put (on, score - 1) 'c' -> put (not on, score) _ -> put (on, score) playGame xs startState = (False, 0) main = print $ evalState (playGame "abcaaacbbcabbab") startState 
+4
source share
2 answers

For quick and dirty debugging, use trace from Debug.Trace . It is often useful for me to reverse the order of the arguments and define

 infixl 0 `debug` debug :: a -> String -> a debug = flip trace 

You can then debug debugging to the end of the line, and it is easier to comment on (and delete at the end).

For more basic logging, combine State with Writer and tell log messages, or use StateT s IO if you want to connect directly to a file or stderr.

+7
source

As nm indicates that there is Debug.Trace , but it's easy to write something yourself. However, I highly recommend using this for debugging only and removing it for real-world code. Here is an example:

 import System.IO.Unsafe output ab = seq (unsafePerformIO (print a)) b (output "test" 23) * 25 -- "test" -- 527 

Here, output takes an argument to print, and the return value behaves like a const , only with a side effect. seq needed to force print to evaluate, otherwise laziness will prevent printing of anything.

+2
source

Source: https://habr.com/ru/post/1392904/


All Articles