简体   繁体   English

如何使 Java class 在 Clojure 中不可变?

[英]How do I make a Java class immutable in Clojure?

I'd like to wrap java's PriorityQueue class in clojure for use in another part of my program.我想在 clojure 中包装 java 的 PriorityQueue class 以用于我程序的另一部分。 What I'm trying to figure out is if there is any way to do this in a lispy manner and make the priority queue immutable.我想弄清楚的是,是否有任何方法可以以 lispy 的方式执行此操作并使优先级队列不可变。 Are there any good ways to do this, or am I just going to be better off using the PriorityQueue as a mutable data structure?有什么好的方法可以做到这一点,或者我只是将 PriorityQueue 用作可变数据结构会更好?

I don't think there is a simple way to wrap a mutable data structure as an immutable one.我认为没有一种简单的方法可以将可变数据结构包装为不可变数据结构。 Immutable data structures become efficient when the new version can share data with the old version in clever ways, and I can't really see how this can be done without access to the internals of PriorityQueue .当新版本可以巧妙地与旧版本共享数据时,不可变数据结构变得高效,如果不访问PriorityQueue的内部结构,我真的无法理解如何做到这一点。

If you really want a persistent priority queuethis thread might be interesting.如果你真的想要一个持久的优先级队列,这个线程可能会很有趣。 Those seems to have linear-time inserts though, so if that is an issue maybe you have to look for another implementation.那些似乎有线性时间插入,所以如果这是一个问题,也许你必须寻找另一个实现。

Edit: On second thought, a simple implementation of a persistent priority queue is just to store the (prio, value)-pairs in a sorted set.编辑:再想一想,持久优先级队列的简单实现就是将 (prio, value) 对存储在排序集中。 Something like this:像这样的东西:

(defn make-pqueue []
  (sorted-set))

(defn pqueue-add [pq x prio]
  (conj pq [prio x]))

(defn pqueue-peek [pq]
  (first pq))

(defn pqueue-pop [pq]
  (let [top (first pq)]
    (disj pq top)))

Of course, the code above is pretty limited (no multiple entries, for instance) but it illustrates the idea.当然,上面的代码非常有限(例如,没有多个条目),但它说明了这个想法。

You can't automagically make mutable class immutable.您不能自动使可变 class 不可变。 One can always call java class directly and mutate it.人们总是可以直接调用 java class 并对其进行变异。

To force immutability you can either implement it in clojure, or extend java class and throw exceptions in all mutable method implementations.要强制不变性,您可以在 clojure 中实现它,或扩展 java class 并在所有可变方法实现中抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM