Favourite piece of Scala code
manufacturist
Posted on October 12, 2023
My favorite piece of Scala code is simple. It's not related to functional programming, typelevel / zio / akka libraries or concurrency.
It simply applies a set of operations on a string, and with the same set of operations, you can reconstruct the original string from the mutated one.
There are three operations: Keep, Insert, and Delete. To represent them as a sequence of operations in JSON, we can assign each operation a type:
- Keep could be a number, indicating how many characters to keep
- Insert can be represented by a string
- Delete can be represented by an array, containing a string element
For example:
mutationLoop([3], "foo") = "foo"
mutationLoop(["foo"], "bar") = "foobar"
mutationLoop([["foo"]], "foobar") = "bar"
// Using them all together
mutationLoop(["foo", 2, ["r"], "z"], "bar") = "foobaz"
When we need to store different versions of a string, we can save space by storing the deltas instead of the full strings. This works well for large strings, but it may not be as useful for smaller strings.
What does the implementation look like?
We need to traverse all operations and apply them one by one:
- For keep, we need to skip a certain number of characters
- For insert, we need to inject a substring into a string
- For delete, we need to remove a substring from a string
Using the circe library, the implementation is as follows:
NB1. The delete operation does not do anything with the string value itself, besides counting the number of characters that need to be deleted. However, it is used when reverting an operation, to recreate the original string
NB2. If we didn't need to be able to revert, instead of an array with a string, we could have specified a negative integer, telling us how many characters we need to remove
To revert the changes, we simply keep the order of the operations, replacing insert operations with delete operations and vice versa:
And putting it to good use:
Why is this my favourite code snippet?
It reminds me of simpler times and humble beginnings, when we didn't take basic building blocks for granted and were mindful of every line of code written, constantly trying to give our best with the little experience we had.
Chef Slowik in the movie The Menu experiences something similar at the end of it, when cooking a cheeseburger. He is reminded of the simple things that ignited his passion for cooking.
Similarly, this snippet of code reminds me of why I enjoy programming.
Posted on October 12, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.