This post is part of a series that’s a work in progress. This is the first post, which is an introduction to the idea of Algebras and how they’re used in Software Development.
The Algebra we all know and love is usually defined as the study of mathematical symbols and the rules for manipulating these symbols. That sounds very pretty and all, but for all of my school years, whenever I heard the word Algebra I thought of variables. You know, x, y and z. With the description in mind though, it all fits really well together. Look at the following, paying close attention to how it reflects the definition given above:
x + x = 2x
It is defining how the
+ works. And by doing that, it’s also defining how addition works and which rules apply to it. So, here’s another one:
x + (y + z) = (x + y) + z
Since that is true for addition, regardless of what values
x, y and z have, we say that addition is Associative. And associativity is a law that needs to be fulfilled whenever we’re adding stuff up. And you know what really tries to follow math a lot? Software. Here are some software examples of operations which are associative:
// In JS: // Addition of numbers is associative 1 + (2 + 3) === (1 + 2) + 3 // true // Multiplication is as well 1 * (2 * 3) === (1 * 2) * 3 // true // String concatenation also works “All” ++ (“ work and” ++ “ no play”) === (“All” ++ “ work and”) ++ “ no play”) // true // Array.prototype.concat also fulfils this. concat([1, 2, 3], concat([4, 5], )) === concat(concat([1, 2, 3], [4, 5]), ) // true
That’s pretty cool. But we can keep going and look for more laws to fulfil. There’s another useful one which is called Identity. An operation fulfils this law if there is a value such that it turns into the Identity Function.
As a refresher, here’s the identity function:
const id = x => x.
And here are the identities for the operation above:
// Addition -> 0 x + 0 === x // Multiplication -> 1 x * 1 = x // String concatenation -> “” (empty string) “Hello World!” ++ “” === “Hello World!” // Array.prototype.concat ->  (empty array) concat([1, 2, 3], ) === [1, 2, 3] /* Ok, that one’s false, but that’s just JS being crazy, ok? The result will still be [1, 2, 3] */
Hail all the maths.
So… why should we care?
I went a bunch of years not really paying attention to any of this and did “fine”. But I could’ve done much better. And that’s the thing, this is not required knowledge for a career in Software Development, but it is something that will make you reason about your code a bit different. When used correctly, it can give you certainty. Just like we never question that
1 + 1 = 2, we could have code that follows laws that assure us certain things will always happen. Doesn’t that sound wonderful?
BTW: the operations we described above are Monoids, one of the weird terms that Functional Programming people keep throwing around. Come back tomorrow for more Monoid fun 🎉