Haskell 中如何实现可变数组?
我读过很多关于这个主题的研究论文,他们通常认为数组是使用 Monad 实现的。但这些论文都没有给出“类型”数组本身应该如何定义的明确定义,它们只给出了使用 monad 访问或修改此类型的函数的定义。 在 Haskell 中如何实现具有 O(1) 时间来访问或修改索引元素的数组?! (例如 STUArray 和 MArray)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它们是通过运行时系统中用于内存读写的原始操作来实现的。
通过使用 monad 线性化对可变状态的访问,可以确保破坏性写入内存的副作用操作的安全性。
查看 Haskell 数组的
primitive
包(在IO
或ST
),您可以看到实现是根据 GHC 的 primops:也就是说,
是用于在语言提供的内存上进行操作的原始(硬件加速;)服务运行时。
Launchbury 和 Peyton-Jones 的论文 惰性功能状态线程,它引入了
ST
monad 和可变数组的原语。They are implemented via primitive operations in the runtime system for memory reads and writes.
The safety of the side effecting action of destructively writing to memory is ensured via the use of monads to linearize access to the mutable state.
Looking at the
primitive
package for Haskell arrays (inIO
orST
), you can see that the implementations is in terms of GHC's primops:That is, in terms of:
which are primitive (hardware accelerated ;) services for operating on memory provided by the language runtime.
Mechanisms for giving type safety to destructive memory effects were introduced to Haskell by the Launchbury and Peyton-Jones paper, Lazy Functional State Threads, which introduces the
ST
monad and primitives for mutable arrays.顺便说一句,请记住,“使用 monad 实现”(可以对各种控制结构执行)与“通过不透明类型上的一元操作隔离的副作用”实际上并不相同,如
IO
或ST
,其中 monad 的属性仅确保纯代码保持不变。正如 Don Stewart 所解释的那样,可变数据作为运行时原语提供;这里唯一“用 monad 实现”的是类型安全。
As something of an aside, please keep in mind that "implemented using monads", as can be done for various control structures, is not really the same thing as "side effects isolated by monadic operations on an opaque type", as with
IO
orST
, where the properties of the monad merely ensure that pure code remains so.The mutable data is provided as a runtime primitive, as Don Stewart explains; the only thing "implemented with monads" here is type safety.
它们的实现方式与命令式语言相同;即就地更新。类型系统将保证你不能用它们做任何“坏”的事情。
They are implemented in the same way as in an imperative language; i.e., in-place update. The type system will guarantee that you can't do anything "bad" with them.