Clojure 中的不可变队列
在 Clojure 中获取简单、高效的不可变队列数据类型的最佳方法是什么?
它只需要两个操作,即使用通常语义的入队和出队。
我当然考虑了列表和向量,但我知道它们在末尾和开头的修改分别具有相对较差的性能(即 O(n) 或更差) - 因此对于队列来说并不理想!
理想情况下,我想要一个适合入队和出队操作的 O(log n) 的持久数据结构。
What is the best way to obtain a simple, efficient immutable queue data type in Clojure?
It only needs two operations, enqueue and dequeue with the usual semantics.
I considered lists and vectors of course, but I understand that they have comparatively poor performance (i.e. O(n) or worse) for modifications at the end and beginning respectively - so not ideal for queues!
Ideally I'd like a proper persistent data structure with O(log n) for both enqueue and dequeue operations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题已解决 - 为其他可能认为有帮助的人提供解决方案。
我发现 Clojure 有 clojure.lang.PersistentQueue 类可以完成所需的工作。
您可以创建这样的实例:
据我所知,您当前需要使用 Java 互操作来创建实例,但正如 Michal 指出的那样,您随后可以使用 peek、pop 和 conj。
Problem solved - solution for others who may find it helpful.
I've found that Clojure has the clojure.lang.PersistentQueue class that does what is needed.
You can create an instance like this:
As far as I can see, you currently need to use the Java interop to create the instance but as Michal helpfully pointed out you can use peek, pop and conj subsequently.
我使用以下函数
queue
来创建一个PersistentQueue。或者,如果您要打印和读取队列,您可能需要一个打印方法和一个数据读取器。通常的 Clojure 函数已经为 PersistentQueue 实现了。
I use the following function
queue
to create a PersistentQueue. Optionally, you might want to have a print-method and a data-reader if you're going to be printing and reading the queues.The usual Clojure functions are already implemented for PersistentQueue.
Clojure 确实可以从队列文字中受益。这比依赖 Java 互操作更干净(并且更可移植)。
然而,创建自己的便携式持久队列并不难,只需使用列表等普通家庭用品即可。
将队列视为两个列表,一个提供队列的头部,另一个提供队列的尾部。
enqueue
添加到第一个列表,dequeue
从后者弹出。大多数ISeq
函数都是简单实现的。也许唯一棘手的部分是当尾部为空并且您想要
出队
时会发生什么。在这种情况下,头列表将被reverse
d并成为新的尾部,而空列表将成为新的头列表。我相信,即使有反向
的开销,enqueue
和dequeue
仍然是O(1)
,不过当然,k
会比普通向量更高。快乐
排队
!Clojure could really benefit from a queue literal. This would be cleaner (and more portable) than relying on Java interop.
However, it's not that hard to roll your own portable persistent queue, just using ordinary household items like lists.
Consider the queue as two lists, one providing the head portion of the queue, and the other the tail.
enqueue
adds to the first list,dequeue
pops from the latter. MostISeq
functions are trivially implemented.Probably the only tricky part is what happens when the tail is empty and you want to
dequeue
. In that case the head list isreverse
d and becomes the new tail, and the empty list becomes the new head list. I believe, even with the overhead of thereverse
, thatenqueue
anddequeue
remainO(1)
, though thek
is going to be higher than a vanilla vector of course.Happy
queue
ing!