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

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.