I recently came across a brief programming puzzle prompt (say that three times fast) which asked to return the year that population peaked.
The actual algorithm to compute it can be done several ways and is not particularly difficult, but I have recently been challenging myself to write .. ahem .. “more functional” code.
There are several tenets of FP, but a chief one is not producing what developers call “side effects”. I’m hoping to get to a point where I do not rely as much on classic object-oriented patterns and feel more at ease diving right into the functional style. Of course this takes practice, so I decided to spend some extra time polishing up my code to meet my internal requirements:
This is a demonstration of what I created after a few minutes of iteration.
I was readily able to produce a list of population changes and from there, performed further transformations to arrive at a list of total populations for each year. From there determining the year that population peaked was trivial.
However, I’m not fully satisfied with this solution. I could be being too dogmatic, but in my mind I would not be breaking scope of a map function to reference external values, even though it proved expedient in this case.
I’ve cross posted this on Stack Exchanges’s CodeReview.
User jwvh posted a great improvement on CodeReview
My favorite part of jwvh’s contribution is the excellent use of foldLeft. After seeing it in practice, and fulfilling the exact tension I felt with my original solution, it motivated me to spend a few hours working through lots, and lots of examples to become proficient at this pattern!