Functional Ruby

Functional Programming through the Ruby veneer

Hamster: Immutable Data Structures for Ruby

Ruby, oh Ruby, so deeply entrenched in mutability one can hardly trust the floor beneath them. Sure, we can have immutability by convention (ie: trust yourself and your team, clearly a foolish thought). Sure, you can kind of address this with calls to Object#freeze. Really though, at the end of the day, wouldn’t it be nice to have a native implementation of immutable data structures in our beloved Ruby? Doubly so, were they performant.

One brave developer out there, Mr. Simon Harris has set out to do just that for us.

Hamster - Efficient, Immutable, Thread-Safe Collection classes for Ruby

Hamster has been under steady development for over 2 years now and provides immutable alternatives to all of Ruby’s built in collection data structures. Hashes, Lists, Sets, Stacks, Tries, Tuples, and Vectors are all there. These are for the most part well documented in Hamster’s readme and spec suite.

Hamster achieves it’s immutability in a fashion similar to Clojure. Any operation that would in a non-functional language mutate the original object, instead will copy that object and return a new one with the updated values in place. While this is achievable with Object#dup, things can get messy quickly, and it certainly doesn’t aid in the readability of your code.

In addition to thread-safety via immutability, we also get the benefit that most operations on Hamster collections are performed lazily so their return values won’t be calculated until necessary. Languages such as Haskell have used this to great effect. In addition to intuitiveness (ie: Why calculate a value that’s unused?), lazy evaluation can sometimes lead to a much clearer expression of certain algorithms.

Is Hamster ready for the prime time? Maybe. Hamster is certainly more mature and documented than some of it’s condtenders. Do check out the readme which does a fine job pointing out potential caveats. It certainly seems worth auditioning for your next project, and since it supports an API pretty similar to native Ruby counterparts, should you have to revert one day I can’t imagine you’d encounter much pain.

If you’re interested in hearing more of what Harris has to says about immutability, you should definitely read Functional Programming in Object Oriented Languages (an excellent blog post in it’s own right).

Comments