Refactor to Functional Style
Our solution works, but the style isn’t very functional. (That’s a polite way of saying it’s butt ugly.) To tidy it up, I look for places where there’s clearly something wrong, and see if I can fix them.
The first problem I see is the first three lines. I’m transforming the given number into a reversed set of digits, each with an associated index.
The word transform is the clue. Functional programming is all about transforming data. It’s so important that Elixir has a special operator, |>. This lets us build pipelines of functions, where each transforms the results of the previous. It lets us compose functionality.
Using the pipeline operator, we can rewrite the first three lines as
| | numbers |
| | |> reverse |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access