Haskell中的所有东西都存储在thunk中,甚至是简单的值? [英] Is everything in Haskell stored in thunks, even simple values?

查看:126
本文介绍了Haskell中的所有东西都存储在thunk中,甚至是简单的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  val = 5  - 下面的值/表达式/函数看起来像在Haskell堆中一样吗? -  val是指向包含5的框的指针? 
add xy = x + y
result = add 2 val
main = print $ result

考虑到懒惰的评估模式,我们很高兴看到这些代码在Haskell中的表现。

正式答案



这不关你的事。

简短回答



是。


$对于Haskell程序本身,答案总是肯定的,但编译器如果发现它可以并且会做不同的事情可以摆脱它,出于性能原因。例如,对于'''添加xy = x + y''',编译器可能会生成与x和y的thunk一起工作的代码,并将thunk构建为结果。
但请考虑以下几点:

  foo :: Int  - > Int  - > Int 
foo xy = x * x + y * y

这里,优化编译器将会生成代码首先将x和y从盒子中取出,然后执行算术运算,然后将结果存储在一个框中。



高级回答



这篇文章描述了GHC如何从一种实现thunk的方式切换到另一种实际上既简单又快速的方式:
http://research.microsoft.com/en-us/um/people/simonpj/papers/eval-应用/


What do the thunks for the following value/expression/function look like in the Haskell heap?

val = 5                -- is `val` a pointer to a box containing 5?
add x y = x + y        
result = add 2 val     
main = print $ result

Would be nice to have a picture of how these are represented in Haskell, given its lazy evaluation mode.

解决方案

Official answer

It's none of your business. Strictly implementation detail of your compiler.

Short answer

Yes.

Longer answer

To the Haskell program itself, the answer is always yes, but the compiler can and will do things differently if it finds out that it can get away with it, for performance reasons.

For example, for '''add x y = x + y''', a compiler might generate code that works with thunks for x and y and constructs a thunk as a result. But consider the following:

foo :: Int -> Int -> Int
foo x y = x * x + y * y

Here, an optimizing compiler will generate code that first takes x and y out of their boxes, then does all the arithmetic, and then stores the result in a box.

Advanced answer

This paper describes how GHC switched from one way of implementing thunks to another that was actually both simpler and faster: http://research.microsoft.com/en-us/um/people/simonpj/papers/eval-apply/

这篇关于Haskell中的所有东西都存储在thunk中,甚至是简单的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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