如何“调试"带有 printf 的 Haskell? [英] How to "debug" Haskell with printfs?

查看:18
本文介绍了如何“调试"带有 printf 的 Haskell?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Ocaml 社区,我正在尝试学习一些 Haskell.过渡进行得很顺利,但我对调试有点困惑.我曾经在我的 ocaml 代码中放置(很多)printf",以检查一些中间值,或者作为标志来查看计算究竟失败的地方.

coming from the Ocaml community, I'm trying to learn a bit of Haskell. The transition goes quite well but I'm a bit confused with debugging. I used to put (lots of) "printf" in my ocaml code, to inspect some intermediate values, or as flag to see where the computation exactly failed.

由于 printf 是一个 IO 操作,我是否必须在 IO monad 中提升所有的 Haskell 代码才能进行这种调试?或者有没有更好的方法来做到这一点(如果可以避免,我真的不想手工做)

Since printf is an IO action, do I have to lift all my haskell code inside the IO monad to be able to this kind of debugging ? Or is there a better way to do this (I really don't want to do it by hand if it can be avoided)

我还找到了 trace 功能:http://www.haskell.org/haskellwiki/Debugging#Printf_and_friends这似乎正是我想要的,但我不明白它的类型:任何地方都没有 IO!有人可以解释一下跟踪功能的行为吗?

I also find the trace function : http://www.haskell.org/haskellwiki/Debugging#Printf_and_friends which seems exactly what I want, but I don't understand it's type: there is no IO anywhere! Can someone explain me the behaviour of the trace function ?

推荐答案

trace 是最容易使用的调试方法.正是因为您指出的原因,它不在 IO 中:无需在 IO monad 中提升您的代码.是这样实现的

trace is the easiest to use method for debugging. It's not in IO exactly for the reason you pointed: no need to lift your code in the IO monad. It's implemented like this

trace :: String -> a -> a
trace string expr = unsafePerformIO $ do
    putTraceMsg string
    return expr

所以在幕后有 IO,但是 unsafePerformIO 被用来逃避它.这是一个可能会破坏引用透明度的函数,您可以通过它的类型 IO a ->一个还有它的名字.

So there is IO behind the scenes but unsafePerformIO is used to escape out of it. That's a function which potentially breaks referential transparency which you can guess looking at its type IO a -> a and also its name.

这篇关于如何“调试"带有 printf 的 Haskell?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆