如何“调试” Haskell与printfs? [英] How to "debug" Haskell with printfs?

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

问题描述

来自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 操作,是否必须将所有我的haskell代码放在 IO monad中才能进行这种调试?或者有更好的方法来做到这一点(我真的不想手工做,如果可以避免)

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)

我也找到了跟踪功能:
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.

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

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