【问题标题】:Haskell - Debug Print in if blockHaskell - 在 if 块中调试打印
【发布时间】:2012-09-23 06:40:42
【问题描述】:

我想通过打印一些东西来调试我的程序

例如,

isPos n 
    | n<0       = False
    | otherwise = True

我想要类似的东西:

isPos n 
    | n<0       = False AND print ("negative")
    | otherwise = True  AND print ("positive")

可以在 Haskell 中做吗?

【问题讨论】:

标签: debugging haskell


【解决方案1】:

正如 hammar 所说,使用 Debug.Trace 模块中的 trace。我发现一个有用的提示是定义函数debug

debug = flip trace

你可以这样做

isPos n
  | n < 0     = False `debug` "negative"
  | otherwise = True  `debug` "positive"

这样做的好处是可以轻松启用/禁用调试打印 在开发过程中。要删除调试打印,只需注释掉其余的 行:

isPos n
  | n < 0     = False -- `debug` "negative"
  | otherwise = True  -- `debug` "positive"

【讨论】:

  • 我也经常发现变体debug = (flip trace) False 很有用。如果我有一个基于守卫的函数定义,我只需插入一个(或多个)| debug ("Interesting value is " ++ show whatever) = undefined 作为第一个守卫。跟踪始终运行,但由于 debug x 始终为 False,因此防护始终失败并且程序运行正常。这使得快速检查值变得容易,至少在已经有保护的函数中是这样。
  • 您还可以在文件顶部有以下两个定义,只需在它们之间切换即可切换调试模式:debug = flip tracedebug a b = a
  • 显然我无法再编辑该评论了;更简单的方法是使用 doDebug 布尔值并将 debug 定义为 debug a b = if doDebug then trace b a else a
【解决方案2】:

使用Debug.Trace.trace

import Debug.Trace

isPos n 
  | n < 0     = trace "negative" False
  | otherwise = trace "positive" True 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多