O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required