Advent of Functional PHP: Day 1

Submitted by Larry on 1 December 2021 - 11:24am

today's challenge asks us to interpret a list of numbers. In the first part, our goal is to determine how many elements in the list are larger than their immediate predecessor.

The imperative way would be to toss it in a `foreach()` loop and track some state along the way. But we want to be functional and avoid "track some state," because the whole point of functional programming is to avoid tracking state, as tracking state is error prone.

When looking at a foreach-style operation that has some state, my first inclination is to look at a reduce operation. A reduce operation walks over a list and performs the same operation (function) on each item, using the output of the previous iteration as an input. That is, each step takes the output of the previous operation and the next element, and produces an output. It's quite elegant.

However, reduction operations only allow you to pass forward one intermediary result. In our case, the input to a given operation is the current element *and* its predecessor. That can be squeezed into a reduction operation if we try, but it feels awkward to me, so I'm going to allow some for-style loops. As long as they're controlled, that's OK.

Let's think about the steps involved in our problem:

  1. Read the input file in from disk.
  2. Break it up into a series of integers (or numeric strings, which for PHP is close enough).
  3. Determine which of those elements is larger than its predecessor.
  4. Count the number of elements that pass the test in step 3.
  5. Profit!

Continue reading this post on PeakD.