【发布时间】:2020-04-10 08:49:06
【问题描述】:
问题:
trace 函数在第二次调用时不起作用,但这只有在包含 trace 的函数被加载到 ghci 时才会发生。
问题
- 为什么会这样?
- 如何在 Haskel 模块中加载并仍然具有预期的行为?
意外行为:
我有一个名为test.hs的文件
import Debug.Trace (trace)
main = trace "test" return "main is called"
然后我在 ghci 中输入以下内容。注意maintrace 的第二次调用没有打印“test”
Prelude> :l test
[1 of 1] Compiling Main ( test.hs, interpreted )
Ok, one module loaded.
*Main> main
test
"main is called"
*Main> main -- No output from trace?
"main is called"
预期行为
但是,如果我在 ghci 中键入 main 函数,我会得到预期的行为
Prelude> import Debug.Trace (trace)
Prelude Debug.Trace> main = trace "test" return "main is called"
Prelude Debug.Trace> main
test
"main is called"
Prelude Debug.Trace> main -- Output from trace
test
"main is called"
Prelude Debug.Trace>
更新
@Robin Zigmond 建议,我尝试了不同的括号但没有成功
main = trace "test" (return "main is called")
main = return(trace "test" "main is called") -- Joins the outputs into one string
【问题讨论】:
-
我不认为我完全理解这种行为 -
trace是一件棘手的事情,因为它基本上打破了 Haskell 的正常规则,以便为您提供调试工具。但我想知道如果你将我想要的表达式括起来,行为是否会改变,如main = trace "test" (return "main is called")。或者可能是main = return (trace "test" "main is called")。您的版本实际上被解析为main = (trace "test" return) "main is called"所以我怀疑函数trace "test" return只需要评估一次。 -
我尝试了你的建议,但没有成功。