How to make Java class immutable in Clojure?

I would like to wrap the PriorityQueue Java class in clojure for use in another part of my program. What I'm trying to understand is if there is any way to do it in a sticky manner and make the priority queue unchanged. Are there any good ways to do this, or will I just be better off using PriorityQueue as a mutable data structure?

+7
java immutability lisp clojure priority-queue
source share
2 answers

I don’t think there is an easy way to wrap a mutable data structure as immutable. Inevitable data structures become effective when a new version can use data with the old version in smart ways, and I cannot figure out how to do this without access to the internal PriorityQueue elements.

If you really need a constant priority queue, this thread can be interesting. However, they seem to have linear time inserts, so if this is a problem, you may have to look for another implementation.

Edit: On the other hand, a simple implementation of a constant priority queue is to simply store (prio, value) pairs in a sorted set. Something like that:

 (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 rather limited (for example, there are not a few entries), but it illustrates the idea.

+8
source share

You cannot automatically make a mutable class immutable. You can always directly call the java class and change it.

For forced immutability, you can either implement it in clojure or extend the java class and throw exceptions in all implementations of mutable methods.

+7
source share

All Articles