查看Haskell中的减少步骤

Shi*_*hiv 14 debugging haskell functional-programming reduction

有没有办法查看haskell中的还原步骤,即跟踪所做的递归函数调用?例如,chez方案为我们提供了trace-lambda.Haskell中有一个等价的形式吗?

eph*_*ent 7

您可以尝试Debug.Trace.trace在要跟踪的位置插入,但这会产生(a)产生严重无序输出的趋势,因为您的trace语句可能属于在远离原始数据之前未评估的thunk调用,以及(b)改变程序的运行时行为,如果跟踪需要评估本来不会被评估的东西(尚未).

这是用于调试吗?如果是这样...


Hat会修改您的源代码以输出可在运行后查看的跟踪.输出应该非常接近你想要的:他们主页上的例子是

例如,计算错误程序

main = let xs :: [Int]
           xs = [4*2,5 `div` 0,5+6]
       in  print (head xs,last' xs)

last' (x:xs) = last' xs
last' [x] = x
Run Code Online (Sandbox Code Playgroud)

给出结果

(8, No match in pattern.
Run Code Online (Sandbox Code Playgroud)

并且可以使用Hat查看工具来探索其行为,如下所示:

  • 帽子堆栈

对于中止的计算,即以错误消息终止或被中断的计算,帽子堆栈显示计算被中止的函数调用.它通过显示函数调用的虚拟堆栈(redexes)来实现.因此,堆栈上显示的每个函数调用都会导致上面的函数调用.顶部堆栈元素的评估导致错误(或在其评估期间计算被中断).显示的堆栈是虚拟的,因为它不对应于实际的运行时堆栈.实际运行时堆栈启用延迟评估,而虚拟堆栈对应于将用于急切(严格)评估的堆栈.

使用与上面相同的示例程序,帽子堆栈显示

$ hat-stack Example
Program terminated with error:
        No match in pattern.
Virtual stack trace:
(Last.hs:6)     last' []
(Last.hs:6)     last' [_]
(Last.hs:6)     last' [_,_]
(Last.hs:4)     last' [8,_,_]
(unknown)       main
$
Run Code Online (Sandbox Code Playgroud)

目前,GHCi(≥6.8.1)还附带一个调试器:

$ ghci -fbreak-on-exception
GHCi, version 6.10.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
Prelude> :l Example.hs
[1 of 1] Compiling Main             ( Example.hs, interpreted )

Example.hs:5:0:
    Warning: Pattern match(es) are overlapped
             In the definition of `last'': last' [x] = ...
Ok, modules loaded: Main.
*Main> :trace main
(8,Stopped at <exception thrown>
_exception :: e = _
[<exception thrown>] *Main> :back
Logged breakpoint at Example.hs:(5,0)-(6,12)
_result :: t
[-1: Example.hs:(5,0)-(6,12)] *Main> :hist
-1  : last' (Example.hs:(5,0)-(6,12))
-2  : last' (Example.hs:5:15-22)
-3  : last' (Example.hs:(5,0)-(6,12))
-4  : last' (Example.hs:5:15-22)
-5  : last' (Example.hs:(5,0)-(6,12))
-6  : last' (Example.hs:5:15-22)
-7  : last' (Example.hs:(5,0)-(6,12))
-8  : main (Example.hs:3:25-32)
-9  : main (Example.hs:2:17-19)
-10 : main (Example.hs:2:16-34)
-11 : main (Example.hs:3:17-23)
-12 : main (Example.hs:3:10-33)
<end of history>
[-1: Example.hs:(5,0)-(6,12)] *Main> :force _result
*** Exception: Example.hs:(5,0)-(6,12): Non-exhaustive patterns in function last'

[-1: Example.hs:(5,0)-(6,12)] *Main> :back
Logged breakpoint at Example.hs:5:15-22
_result :: t
xs :: [t]
[-2: Example.hs:5:15-22] *Main> :force xs
xs = []
Run Code Online (Sandbox Code Playgroud)

虽然不那么好,但它具有易于使用的优点,并且无需重新编译代码即可使用.