了解GHCi让绑定参与时thunk的不同行为 [英] Understanding the different behavior of thunks when GHCi let bindings are involved

查看:172
本文介绍了了解GHCi让绑定参与时thunk的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩Simon Marlow关于Haskell中并行和并发
编程的书中的一些例子,并偶然发现了一个我不太了解的有趣行为。我真的想了解一些GHC的内部工作。



假设我在REPL中执行以下操作:

 λ»让x = 1 + 2 :: Int 
λ»让z =(x,x)
λ»:sprint x
x = _
λ»:sprint z
z =(_,_)
λseq x()
()
λ»:sprint z
z =(3,3)

好的,这是我所期望的,除了z已经被评估为WHNF。让我们编写一个类似的程序,并把它放在一个文件中:

  module Thunk其中

导入调试。 Trace

x :: Int
x = traceadd$ 1 + 2
$ b $ ::(Int,Int)
z =(x,x)

然后在GHCi中捣鼓它:

 λ»:sprint x 
x = _
λ»:sprint z
z = _
λ»seq x()

()
λ::sprint z
z = _
λseq z()
()
λ»z
(3,3)

所以这有点不同: z 不会预先评估为WHNF。我的问题是:

为什么在执行时,在REPL中将 z 评估为WHNF z =(x,x),但从文件加载定义时不适用。我怀疑是
它与模式绑定有关,但我不知道该在哪里寻找澄清(也许我完全错了)。我希望它能像文件中的例子那样行事。



任何指针或简单解释为什么发生这种情况?

(,)是一个构造函数,所以它与Haskell的语义没有什么不同(:sprint 可以访问内部的thunk实现细节,因此不会计数)。所以这是一个GHC在编译时使用哪种优化和权衡的问题(x,x )在不同的位置。其他人可能知道这些情况下的确切原因。


I've been playing with some examples from Simon Marlow's book about parallel and concurrent programming in Haskell and stumbled across an interesting behavior that I don't really understand. This is really about me trying to understand some of the inner workings of GHC.

Let's say I do the following in the REPL:

λ» let x = 1 + 2 :: Int
λ» let z = (x,x)
λ» :sprint x
x = _
λ» :sprint z
z = (_,_)
λ» seq x ()
()
λ» :sprint z
z = (3,3)

Ok, this is pretty much what I expected except that z gets evaluated to WHNF already. Let's write a similar program and put it in a file:

module Thunk where

import Debug.Trace

x :: Int
x = trace "add" $ 1 + 2

z :: (Int,Int)
z = (x,x)

And fiddle around with it in GHCi:

λ» :sprint x
x = _
λ» :sprint z
z = _
λ» seq x ()
add
()
λ» :sprint z
z = _
λ» seq z ()
()
λ» z
(3,3)

So this behaves a little different: z is not evaluated to WHNF in advance. My question is:

Why is z evaluated to WHNF in the REPL when doing let z = (x,x) but not when loading the definition from a file. My suspicion is that it has something to do with pattern binding but I don't know where to look that up for clarification (maybe I'm just completely utterly wrong). I would have expected it to somehow behave like the example in the file.

Any pointers or a brief explanation why this happens?

解决方案

Because (,) is a constructor, the difference makes no difference to Haskell's semantics (:sprint gives access to internal thunk implementation details so doesn't count.) So this is a question of which optimizations and trade-offs GHC does when compiling (x,x) in different positions. Someone else may know the precise reason in these cases.

这篇关于了解GHCi让绑定参与时thunk的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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