Advent of Functional PHP: Day 1 – Larry Garfield

Advent of Functional PHP: Day 1

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.

Larry
1 December 2021 – 11:24am