Stumbled across this problem set Day 1 - Advent of Code 2021. Problems that are to be solved daily before Christmas. It's a bit of fun to do one or two, but it would be too masochistic of me to do one each day before Christmas. I'd rather go to the gym or do a workout in my spare time. Health and fitness is important to me, and with the lockdowns and winter, bad habits, bad drinking and bad eating took charge.
I decided to do the first problem in F# since that will be my main language for the forseeable future, and it's an opportunity to practice using the language idiomatically. I'm going to avoid talking about the problem itself. You can read it at the link above. What I want to highlight in the solution are the following:
- Evolution from recursion to fold.
The solution for both parts of the question is here: adventofcode2021/Program.fs at master · sashang/adventofcode2021 (github.com)
Note the evolution from the initial tail-recursive implementation that tracked the previous value and count using an accumulator parameter. Once I had the tail recursive function written the core of it became the folder, the function that you pass to
List.fold. Whenever you see that pattern in your code think How can I can use a fold here?. A
fold function is used for handling state within a loop.