| > I made a half-hearted attempt to learn Haskell Try Clojure(script) - everything that felt confusing in Haskell becomes crystal clear, I promise. > Consider a histogram function. You can absolutely do this efficiently with immutable structures in Clojure, something like (reduce (fn [acc x]
(update acc x (fn [v] (inc (or v 0)))))
{}
coll)
This is O(n) and uses immutable maps. The key insight: immutability in Clojure doesn't mean inefficiency. Each `update` returns a new map, but:1. Persistent data structures share structure under the hood - they don't copy everything 2. The algorithmic complexity is the same as mutable approaches 3. You get thread-safety and easier reasoning for a bonus In JS/TS, you'd need a mutable object - JS makes mutability efficient, so immutability feels awkward. But Clojure's immutable structures are designed for this shit - they're not slow copies, they're efficient data structures optimized for functional programming. |
You are still doing a gazillion allocations compared to:
But apart from that the mutable code in many cases is just much clearer compared to something like your fold above. Sometimes it's genuinely easier to assemble a data structure "as you go" instead of from the "bottom up" as in FP.