我写了一个 Haskell 程序,它对列表进行二分查找.至少我是这么认为的.当我用 ghc v7.6.3 编译程序并运行程序时,我得到以下输出:
I wrote a Haskell program that preforms a binary search on a list. At least that's what I thought it does. When I compiled the program with ghc v7.6.3 and ran the program I got the following output:
progname: <<loop>>这个输出到底是什么意思?这是否意味着我有一个 ghc 优化掉的无限循环?我该如何调试?
What on earth does this output mean? Does it mean I had an infinite loop that ghc optimized away? How am I supposed to debug this?
推荐答案正如一些评论所说,这是 Haskell RTS 在运行时检测无限循环.它不能总是检测到这样的循环,但在简单的情况下可以.
As several of the comments have said, this is the Haskell RTS detecting an infinite loop at run-time. It cannot always detect such loops, but in simple cases it can.
例如
x = x + 1会编译得很好,但会在运行时引发异常.(顺便说一句,这是一个例外 - 特别是,如果您愿意,您可以捕获它.但您可能并不想要".)
will compile just fine, but provoke an exception at run-time. (Incidentally, this is an exception - in particular, you can catch it if you want. But you probably don't "want".)
那么为什么 GHC 甚至让这个编译?好吧,因为如果我用 : 替换 +,那么表达式现在终止就好了.(它代表一个 1 元素的循环列表.)编译器无法在编译时判断什么是合理的递归,什么是不合理的递归.RTS 不能总是在运行时判断;但是当它可以告诉你有什么问题时,它会通过向你抛出异常来让你知道.
So why does GHC even let this compile? Well, because if I replace + with, say, :, then the expression now terminates just fine. (It represents a 1-element circular list.) The compiler can't tell at compile-time what is and is not sensible recursion. The RTS can't always tell at run-time; but when it can tell something's wrong, it'll let you know by throwing an exception at you.
更多推荐
Haskell 程序输出 `<<loop>>`
发布评论