By now you have probably heard all the hype about functional programming (FP) and may have even dipped your toe in the water by trying out Clojure or one of the other Lisp dialects.
Maybe you have experimented with some of the functional elements of Scala, Ruby, Python, or one of the newer languages like Swift. If you are a long time imperative programmer like me, your first exposure to functional programming may have left you feeling a bit bewildered and not quite sure if you are smart enough for FP.
Maybe you have convinced yourself that FP is only for academics or guys that win Turing Awards. Maybe you have even convinced yourself that you don’t really need to learn it at all, that it’s just the latest craze and that if you wait long enough something else will come along. After all, FP languages don’t even make the top ten on the latest RedMonk listings.
First the bad news: functional programming isn’t going to disappear any time soon. FP tenets like immutable data, referential transparency, higher order functions, function composition, etc., lend themselves to building highly scalable software that can take advantage of this distributed, multi-core world in which we find ourselves. I’m not just repeating the FP mantra here; this is based on personal observations made while spending the last two years rebuilding a legacy JRuby system in Clojure. Now the good news: you don’t have to be a genius like Rich Hickey to be a functional programmer.
This is the prologue to a series of posts for those of us who aren’t quite sure we are clever enough to be functional programmers. In this series I’ll cover a set of example programming tasks that often seem challenging when moving from an imperative style to FP. For each example I will first present a solution in an imperative language, Java, and then present a solution using a functional language, Elixir. I’ll highlight the differences in each approach and explain the rationale and benefits of the FP solutions.
Many of you have probably never seen Elixir code (or even heard of Elixir), but I think it makes a great choice for learning FP for several reasons. First, it borrows a lot of syntax from Ruby, so it may be more accessible to Rubyists than the Lisp dialects. Second, it runs on the Erlang VM (BEAM), which has quick startup and generally makes for a snappier development experience than say JVM based languages. Finally, although it’s only a few years old, the documentation and tooling around Elixir are excellent, including a powerful REPL (Read-Eval-Print-Loop) with good editor integration.
Hopefully by the end of this series you will realize that “thinking functionally” is not strictly the domain of the intelligentsia, and that FP is not only within your reach, but worth reaching for. In the next article we will look at a common task, iterating over a collection, which should be familiar using an imperative approach, but can be confusing at first using FP.