观察哈斯克尔的懒惰 [英] Observing lazyness in Haskell

查看:146
本文介绍了观察哈斯克尔的懒惰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以编写一个Haskell函数,取决于值是已经计算好还是为thunk?例如。如果 lazyShow :: [Int] - >字符串通常显示thunk为和计算值,在GHCi中我们会看到

Is it possible to write a Haskell function which depends on whether values are calculated already or are thunks? E.g. if lazyShow :: [Int] -> String shows thunks as ? and calculated values normally, in GHCi we would see

> let nats = [0..]

> lazyShow nats
0 : ?

> nats !! 5    
5

> lazyShow nats
0 : 1 : 2 : 3 : 4 : ? 


推荐答案

显然, lazyShow 不能拥有你所说的类型。如果字符串应该取决于评估的当前状态,那么 IO字符串因此是您所期望的最好的。

Clearly, lazyShow cannot have the type you state. If the string should depend on the current state of evaluation, then IO String as a result is the best you can hope for.

如果你感兴趣的是使用它进行调试,那么我认为 ghc-heap- (可能为图形前端,例如 ghc-vis )可用于此目的。它定义了一个GHCi命令:printHeap ,可用于显示该值在GHC堆中的显示方式。这可能比您想要的要低一点,但更好地理解懒惰评估和分享的工作方式会非常有用:

If all you're interested in is using this for debugging, then I think that the ghc-heap-view package (and potentially a graphical frontend such as ghc-vis) are useful for this purpose. It defines a GHCi command :printHeap that can be used to display a description of how the value looks in GHC's heap. It's perhaps a bit more low-level than what you intended, but it can be quite useful to understand better how lazy evaluation and sharing work:

Prelude> let nats = [0..]
Prelude> :printHeap nats
(_bco (D:Enum _fun _fun _fun _fun _fun _fun _fun _fun) _fun)()
Prelude> null nats
False
Prelude> System.Mem.performGC
Prelude> :printHeap nats
let x1 = S# 0
in x1 : _thunk x1 (S# 1)
Prelude> nats !! 5
5
Prelude> System.Mem.performGC
Prelude> :printHeap nats
let x1 = S# 5
in S# 0 : S# 1 : S# 2 : S# 3 : S# 4 : x1 : _thunk x1 (S# 1)

我通过 System.Mem.performGC (按照ghc-heap-view的文档中的建议)清理视图。

I'm explicitly calling the garbage collector via System.Mem.performGC (as recommended in the documentation of ghc-heap-view) to clean up the view a bit.

这篇关于观察哈斯克尔的懒惰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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