打印状态值进行调试
我们如何打印当前状态值以进行调试?例如,在http://www.haskell.org/haskellwiki/State_Monad<的concrete-example-1的代码中/a> ,如何在读取每个输入字符后打印当前状态值?
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
How can we print current state value, for debugging purposes? E.g., in code from concrete-example-1 of http://www.haskell.org/haskellwiki/State_Monad , how can we print the current state value after each input character is read?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要进行快速而肮脏的调试,请使用
Debug.Trace
中的trace
。我经常发现翻转参数顺序并定义很有用,然后您可以将调试添加到行尾,并且更容易注释掉(并在最后删除)。
对于更有原则的日志记录,请将
State
与Writer
结合起来,并tell
记录消息,或者使用StateT s IO
if您直接想要记录到文件或 stderr。For quick and dirty debugging, use
trace
fromDebug.Trace
. I often find it useful to flip the argument order and defineThen you can tack the debugging to the end of the line and it's easier to comment out (and at the end remove).
For more principled logging, combine the
State
with aWriter
andtell
the logging messages or useStateT s IO
if you directly want to log to a file or stderr.正如 nm 指出的那样,有 Debug.Trace,但自己编写一些东西很容易。不过,我强烈建议仅将其用于调试,并在实际代码中将其删除。这是一个示例:
这里
output
接受一个要打印的参数和一个返回值,其行为类似于const
,只是有副作用。需要seq
来强制对print
进行评估,否则惰性将阻止打印任何内容。As n.m. points out there is
Debug.Trace
, but it's easy to write something yourself. However I strongly recommend to use this only for debugging, and to remove it for real world code. Here is an example:Here
output
takes an argument to print out, and a return value, behaving like aconst
, just with a side effect.seq
is needed to force the evaluation ofprint
, else laziness will prevent to print anything.