谁能解释GHC对IO的定义? [英] Can anybody explain GHC's definition of IO?
问题描述
标题非常具有描述性,但是有一部分引起了我的注意:
The title is pretty self-descriptive, but there's one part that caught my attention:
newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
剥离newtype
,我们得到:
State# RealWorld -> (# State# RealWorld, a #)
我不知道State#
代表什么.我们可以用State
代替它吗?
I don't know what State#
stands for. Can we replace it with State
like this:
State RealWorld -> (State RealWorld, a)
那么可以这样表示吗?
State (State RealWorld) a
这种特殊的结构引起了我的注意.
This particular construct caught my attention.
从概念上我知道,
type IO a = RealWorld -> (a, RealWorld)
@ R.MartinhoFernandes告诉我,我实际上可以将该实现视为ST RealWorld a
,但是我很好奇为什么特定的GHC版本是这样写的.
And @R.MartinhoFernandes told me that I can actually think about that implementation as ST RealWorld a
, but I'm just curious why the particular GHC version is written like it is.
推荐答案
最好不要对GHC的IO
实现过分思考,因为这种实现很奇怪而且很阴暗并在大多数情况下通过编译器的运气和运气工作. GHC使用的残缺模型是IO
动作是从整个现实世界的状态到与整个现实世界的新状态配对的值的函数.要幽默地证明这是一个奇怪的模型,请参见 acme-realworld
程序包.
It's probably best not to think too deeply about GHC's implementation of IO
, because that implementation is weird and shady and works most of the time by compiler magic and luck. The broken model that GHC uses is that an IO
action is a function from the state of the entire real world to a value paired with a new state of the entire real world. For humorous proof that this is a strange model, see the acme-realworld
package.
这种工作方式":除非导入名称以GHC.
开头的怪异模块,否则您将无法触摸任何这些State#
内容.您仅获得对使用IO
或ST
处理的功能的访问权限,并确保不能重复或忽略State#
.此State#
贯穿程序,以确保I/O原语实际上以正确的顺序被调用.由于所有这些都是假装,所以State#
根本不是一个正常值-它的宽度为0,占用0位.
The way this "works": Unless you import weird modules whose names start with GHC.
, you can't ever touch any of these State#
things. You're only given access to functions that deal in IO
or ST
and that ensure the State#
can't be duplicated or ignored. This State#
is threaded through the program, which ensures that the I/O primitives actually get called in the proper order. Since this is all for pretend, the State#
is not a normal value at all—it has a width of 0, taking 0 bits.
为什么State#
接受类型参数?那真是太漂亮了. ST
使用它来强制保持状态线程分离所需的多态性.对于IO
,它与特殊的魔术RealWorld
类型参数一起使用.
Why does State#
take a type argument? That's a much prettier bit of magic. ST
uses that to force polymorphism needed to keep state threads separate. For IO
, it's used with the special magic RealWorld
type argument.
这篇关于谁能解释GHC对IO的定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!