Haskell:是否有比 MArray 更通用的键/值存储类?
我不确定我是否低估了 MArray 与否,但对于我实现的许多算法来说,我关心的是我有一些用于存储键/值对的数据结构。显然,数据结构的选择会影响性能,但最好先编写算法,然后根据需要优化数据结构。
我真正想要的是一个像这样的类型类:
class Monad m => MStore m k v where
putAt :: k -> v -> m ()
getAt :: k -> m v
-- and possibly
pairs :: m [(k,v)]
所以我的算法可以操作 k
类型的东西,而不必担心它是否是 Text
并且我需要使用哈希表,或者过度概括并且错过了 Int 键的数组优化性。
I'm not sure if I'm underestimating the power of MArray or not, but for a lot of algorithms I implement, all I care about is that I have some data structure for storing key/value pairs. Obviously the choice of data structure will impact performance, but it'd be nice to just write the algorithm first, and work on optimizing the data structure as needed.
What I'd really like is a typeclass like:
class Monad m => MStore m k v where
putAt :: k -> v -> m ()
getAt :: k -> m v
-- and possibly
pairs :: m [(k,v)]
So my algorithm can manipulate things of type k
without worrying if it's Text
and I need to use a hashtable, or over generalizing and missing out on the array optimizability of Int
keys.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只是为了回应评论,确实没有常用的东西。快速&肮脏的解决方案是在本地定义 putAt、getAt 和pair 作为当前选择的数据结构上适当函数的别名。然后,您可以通过重新定义函数来交换到新的数据结构(如果您为数据结构使用类型别名,那么您可以使用类型签名,而无需重新定义它们)。这只是一个动态抽象数据类型。如果您愿意,可以切换到新类型以正确执行 adt。
请注意,edison 库(基于 Oksaki 在函数式数据结构方面的工作)尝试提供通用容器 API,但该 API 实际上仅针对 edison 提供的结构实现:http://hackage.haskell.org/package/EdisonAPI
Just to echo the comments, there really isn't such a thing in common use. A quick & dirty solution is to define putAt, getAt, and pairs locally as aliases to appropriate functions on your current data structure of choice. Then you can just swap to a new data structure by redefining the functions (and if you use a type alias for your data structure, then you can use type signatures without having to redefine those either). This is just an abstract-data-type by convention on the fly. You can switch to a newtype to enforce the adt properly if you like.
Note that the edison library (based on Okasaki's work on functional data structures) attempts to provide a general containers API, but the API is really only implemented for the structures provided by edison: http://hackage.haskell.org/package/EdisonAPI