Building collections: Immutable Clojure vs mutable OOP

In traditional OOP, if you have some collection A and based on the elements of A you need to build another collection B, a common approach is instantiating B as an empty collection, iterating over A and at each iteration appending a new element to B. When working with Clojure I had to invite a new way of thinking about this sort of task.

To demonstrate the two approaches, I've thrown up equivalent solutions to the same task in both PHP and Clojure. The task defines a map whose keys are years and values are structures which contain 2 integers (liabilities and equity). The goal is to calculate assets (the sum of liabilities and equity) of each year and just put them in another structure: an array in PHP and a list in Clojure. The original structure, of course, needs to remain intact.

The following is the version in PHP which loops through one structure and mutates another.

Now, the interesting part. In Clojure, as data structure are immutable you cannot instantiate an empty structure and keep appending elements to it. Operations on a map yields a new map. This means we can freely do whatever transformations we want on the original map defined in the task. The following implementation in Clojure "replaces" the map values (BalanceSheet with liabilities and equity) by a simple integer (assets). The resulting map is passed to vals and a list of assets is returned.

The takeaway is this: in Clojure it is not necessary to "grow" a structure to reach its desired state. Instead, applying transformations on an existing structure can be enough.

Popular posts from this blog

AWS VPN Client on a guest VM

Cyberghost Vpn on Arch Linux