Posts

Showing posts from August, 2021

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 s...