Hi all,
Nowadays it is very common to see people discussing the use of functional programming, most of modern languages adopt some of its principles and seems that it is a new shift that will change the way you program, but definitely isn’t. Functional programming has been around for a long time, the first functional language was LISP back in 1959 and since then there are some misconceptions and confusions about the idea of functional programming that leads to misuse of a very useful paradigm but that isn’t a silver bullet. People with background in imperative programming where the solution for an algorithm should be described step by step in a sequence of statements tend to feel love at first sight with functional programming due to the fact of writing much less code to achieve the same results and ease of reading.
Principles of Imperative Programming
To a better understand of Functional Programming let’s see what are the principles of Imperative Programming, so we can have a trade between both. Basically Imperative Programming deals with:
- Modifying mutable variables
- Using assignments
- Control structures such as if-then-else, loops, breaks, continue, return
As mentioned by Martin Odersky in Functional Principles with Scala the most common informal way to understand imperative programs is a instruction sequences for a Von Neumann computer. So, what’s wrong here? The problem with Imperative Programming is its nature of changing states. Dealing with huge imperative applications can be extreme improductive to be sustained once scaling is a big problem when shared mutable state is on the scene.
What is Functional Programming?
One of the misconceptions that we can mention about functional programming is the fact that it is a replacement for object oriented programming. Definitely NOT…repeat it to yourself 3 times. There is no contradiction with OO (Scala use both for example), rather, you can use object oriented design with a functional implementation. Functional programming is a paradigm focused in how should be the structure of the implementation, so, instead of describing all the steps to perform an action ending in a low level and verbose code, functional is more concise, easier and expressive. I came from OOP with imperative background and right in my first experiments with FP in Scala I was really excited, imagine a language with wich you code as simple as reading? Now Java 8 has the new syntax of Java 8 with Lambda expressions which I just met but I always worked with Java’s previous versions that everything is so verbose, let’s see a small example of iterating through a list.
Even the syntax of enhanced loop isn’t so clear but brought a huge improvement in terms of reading. Under the hood the enhanced for uses the Iterator Interface calling hasNext() and next() methods.
Noticed how is more readable? Makes more sense and clearly you can identify the meaning of that execution in terms of purpose but, thats just one of the characteristics of FP used to show the difference from an imperative to a functional paradigm in coding. The definition of FP isn’t so clear but there are some features that can’t be forgot when talking about the benefits of FP. According to Gilad Bracha in (one brilliant presentation about what is and what isn’t FP, the definitions of FP vary, but tend to involve High Order Function and Abscence of effects.
Those 2 things are really in the core of FP. Abscence of effects is directly related with immutability and one of the most important things when working with functions and you know that’re prepared for the shift to FP when abscence of effects is automatic in your mind when modelling your functions, I’d enumerate others points to understand if you want to really dig into FP, that are:
- First Class Functions
- Pure Functions
- Immutable variables
- Currying
- Tail Recursion
- Pattern Matching
- Monads
So, let’s see a brief explanation and a small example of each one in Scala of the above
First Class Functions
First Class Functions are functions treated as objects themselves. It can be passed as a parameter to another function, return a function from a function or store a function in a variable. Functions which take other functions as parameter or return them are also known as High Order Function. Here is a small example, i decided to use Javascript for ours examples because it is a well known language and available in all modern browsers so you can easily open your browser and test the code.
In the example above we created a variable called myFunction and assigned an Anonymous Function which sum two values. After I defined a function called sumAllValues where return the sum of his parameters that in our case one of them is the Anonymous Function assigned to myFunction variable, this is our small example of first class functions.
Pure Functions
Pure Functions is a mathematical concept that relies on the fact that a function always evaluates the same value given the same arguments. In our subject it is directly associated with mutability and side effects or the absence of them. In FP we should not mutate variable values that are passed as parameters inside our functions and a function should be designed to always perform the same computation, resulting in the same output given a set of inputs. Larger functions tends to be hard to maintain and error prone, in a good functional design a function does exactly one computation and return the value of it.
Immutable Variables
Immutable variables is a concept in the core of Functional Programming. It is related with side effects like Pure Functions, in therms of multi-thread applications an immutable object is totally reliable once it can’t have his value changed so, if you want to change a value from a immutable object you should create a new one and reference to it. Immutable variables is not just a good practice in FP, languages like Java has lot of immutable classes in his core, String is a classical example.
Currying
Currying is a technique of changing the number of parameters of a function, so for example if a function has 5 parameters you can change it to one parameter. Currying is used behind the scenes in the High Order Functions mentioned above to simplify and reuse functions. Let’s see a practical example with Javascript code:
The code above is a classical example where a function called pow that takes two parameters is used inside the square function instead of redoing his algorithm inside square function. As mentioned above, it enhances the flexibility and reuse of functions.
When understanding these topics, you’ll start to take advantage of FP principles and have a better coding with more pleasure and less error prone. Probably you’ll never want get back to old imperative way and will notice yourself thinking functional for solving problems that you used to have. When its happen you’ve been bitten by the functional bug ;)
For Further Reading
If you want to go further, you can start by the John Backus paper Can Programming Be Liberated From the Von Neumann Style? A Functional Style and Its Algebra of Programs. where, back in 1977 he discusses some application for FP. Other good reference is the already mentioned presentation of Gilad Bracha where he explains how to distinguish FP hype from reality and to apply key ideas of FP in non-FP languages, separating the good parts of FP from its unnecessary cultural baggage. What really made me fell confortable with FP as a beginner was the Martin Odersky course at Coursera called Functional Principles with Scala that I mentioned before in this article. In this course you’ll have a good understand of the difference between
Currently I’m reading the following book and finding it really helpful with good explanation about principles and techniques
And you, from where you suggest to start with functional?