Question

I am planning to improve my knowledge of Clojure and algorithms at the same time by implementing some known data structures in Clojure (e.g. linked lists, skip lists, bloom filter, etc.). However, I learned recently that this might not be a good idea.

[... T]he fact that getting an optimized solution is so difficult should be a sign that's somethings wrong. In the ~2 years that I've been writing Clojure, I've never written my own basic structure. In most other languages, it's a very common exercise. In Clojure though, the lower level implementation of the structures used are best tucked away somewhere, and it's much more common to just use the basic structures of the language.

This was also kind of how I felt while implementing the linked list. Of course, I know since this is only an exercise and not production code, it does not matter too much if the code is optimal or not, or there is already a better built in solution or not. On the other hand, I wouldn't want to waste time on something that does not make sense.

I know this question might be tagged as opinion-based, and therefore without a clear answer. However, imagine I asked: "Is assembly the right choice for implementing the back-end part of an average web-app?". While this second question is also "opinion-based", I cannot imagine that the answer would be "yes", (well, except maybe for some very-very-very specific edge case.) That's why I hope that my question also has a clear yes/no answer.

Was it helpful?

Solution

Traditional data structures are mutable by nature. You manipulate them by changing pointers/references and modifying their contents. That's hard to do in an immutable language; you essentially have to replace the data structure with a new one.

Closure itself doesn't even stick to immutability when using its own internal data structures:

Clojure data structures use mutation every time you call, e.g. assoc, creating one or more arrays and mutating them, before returning them for immutable use thereafter. The reason is performance - you simply can’t get as fast using only pure functions and immutable data.

Your choice, therefore, is choosing a different language for learning basic data structures, or writing them in an immutable style, in the vein of Okasaki's Purely Functional Data Structures.

Further Reading
Transient Data Structures

Licensed under: CC-BY-SA with attribution
scroll top