如何调试 Haskell 代码? [英] How to debug Haskell code?

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

问题描述

我有问题.我写了一个很大的 Haskell 程序,它总是在小的输入下工作.现在,当我想测试它并生成更大的输入时,我总是收到消息:

I have a problem. I wrote a big Haskell program, and it always works with small input. Now, when I want to test it and generate a bigger input, I always get the message:

HsProg: Prelude.head: empty list

我多次使用Prelude.head.我该怎么做才能找到更多信息或获得更好的错误输出以获取发生错误的代码行?

I use Prelude.head many times. What can I do to find out more or get a better error output to get the code line in which it happens?

推荐答案

GHCi 选项 -fbreak-on-exception 很有用.这是一个示例调试会话.首先,我们将文件加载到 GHCi 中.

The GHCi option -fbreak-on-exception can be useful. Here's an example debugging session. First we load our file into GHCi.

$ ghci Broken.hs
GHCi, version 7.0.2: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
[1 of 1] Compiling Main             ( Broken.hs, interpreted )
Ok, modules loaded: Main.

现在,我们打开 -fbreak-on-exceptions 并跟踪我们的表达式(在本例中为整个程序的 main).

Now, we turn on -fbreak-on-exceptions and trace our expression (main in this case for the whole program).

*Main> :set -fbreak-on-exception
*Main> :trace main
Stopped at <exception thrown>
_exception :: e = _

我们遇到了一个异常.让我们试着用 :list 看代码.

We've stopped at an exception. Let's try to look at the code with :list.

[<exception thrown>] *Main> :list
Unable to list source for <exception thrown>
Try :back then :list

因为Prelude.head发生了异常,所以不能直接看源码.但是正如 GHCi 告诉我们的那样,我们可以去 :back 并尝试在跟踪中列出之前发生的事情.

Because the exception happened in Prelude.head, we can't look at the source directly. But as GHCi informs us, we can go :back and try to list what happened before in the trace.

[<exception thrown>] *Main> :back
Logged breakpoint at Broken.hs:2:23-42
_result :: [Integer]
[-1: Broken.hs:2:23-42] *Main> :list
1  
2  main = print $ head $ filter odd [2, 4, 6]
3  

在终端中,有问题的表达式 filterodd [2, 4, 6] 以粗体突出显示.所以这是在这种情况下评估为空列表的表达式.

In the terminal, the offending expression filter odd [2, 4, 6] is highlighted in bold font. So this is the expression that evaluated to the empty list in this case.

有关如何使用 GHCi 调试器的更多信息,请参阅 GHC 用户指南.

For more information on how to use the GHCi debugger, see the GHC User's Guide.

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

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