Functional Programming 101

Yannick S
5 min readFeb 11, 2016

--

Hi there, here a post about basic principles of Functional Programming.

I decided to compile what I learned on that field that helped me grasp complex FP concepts easily.

The following code examples will be written in JavaScript.

Functional programming ?

Functional programming has been around forever but only recently it has been gaining a lot of traction thanks to the explosion of Cloud-computing and the need for scalability and high performance.

But even if, you do not work in the cloud, FP can make you a better and more efficient programmer. 😉

Functional programming a programming paradigm based on the use of functions and function composition.

It will help you write better programs and reason about the problems you have to solve.

It may look like hieroglyphs at first when coming from an imperative background, but when you take the time to understand its common concepts and to practice it, it becomes a extremely valuable asset in your problem solving toolkit.

This paradigm provides support for purity and/or first-class functions.

Let’s define new concepts ! 🤓

Vocabulary

Purity

A pure function is a function where there is only one possible result for each combination of arguments (without any other effect).

This constraint means :

  • A pure function can’t have any side-effects, therefore it is independent from the context.
function pureFunc(x) { 
return 2 * x
}
var y = 2

function impureFunc(x) {
y = y + x return y
}
  • Pure functions can be evaluated in any order, the result is always the same. Therefore, pure functions calls can be run in parallel. (Thx Matteo Ronchetti 😉)
let multByTwo = (x) => 2 * xlet addThree = (x) => x + 3addThree(2)  // -> 5
multByTwo(2) // -> 4
/* Reverse order */multByTwo(2) // -> 4
addThree(2) // -> 5
  • A call of a pure function can be replaced anytime by its unique result. This is Referential transparency.
addThree(3) === (3 + 3)// -> true

But it provides useful benefits :

  • Simpler unit testing (no need of fixtures — just test your functions isolated!)
  • Readability
  • Static analysis and validation checking is made easier (good for IDEs/Linters)

Purity requires a some discipline to enforce it in our programs. The use of purity is not so easily adopted, despite the benefits it induces in application development.

First-class functions

In Functional Programming, a function is first-class citizen.

Being a first-class means having the same properties as plain values (like integers, strings, etc):

  • They can be named, or assigned to a named object.
function namedFunc (x) { … }SampleObject.method = function () { … }
  • They can be passed as an argument of a function.
function addTwo (x) { return x + 2 }function logger (f, value) { 
console.log(f(value))
}
logger(addTwo, 2)// -> 4
  • They can be the result of a function.
function namedFunc () { 
return function () { … }
}
  • They can be stored in any kind of data structure.
function f (x) { … } 
function g (y) { … }
function h (z) { … }
var array = [f, g, h]

Because of property (2), first class functions can be described in an “anonymous form”.

These are called functional values, anonymous functions, or lambda expressions.

First-class citizenship and purity are distinct properties.

Some languages choose to enforce pure FP (e.g. Haskell), and some other choose to mix first-class functions with imperative features and not to care about enforcing purity (e.g. Scala, Python, Javascript, C#, Swift, Java, …). These are multiparadigm languages.

Closures

A closure is the association of a function code with a set of definitions and bindings from the lexical scope (an enclosed environment).

A closure is defined at the function declaration step.

Closures have access to the outer function’s variable even after the outer function returns: The inner function still has access to the outer function’s variables even after the outer function has returned.

Let’s describe the concept of closure with an example :

function outer(word) {
return function inner() {
return word + ' ?'
}
}
var question = outer('Really')
// this returns the 'inner' function
question()// -> 'Really ?'

We store the inner function inside the question variable, and then when we call it still has access to the variables and arguments of the outer function, even if it has already returned.

If we pause the execution in Chrome Devtools :

We can see that the inner function has access to a closure from outer, and it contains the word variable.

This is why we talk about “Closure”. The lexical scope (variables) is enclosed in the inner function.

Functional != Imperative ?

Imperative programming is the most dominant paradigm and the most used in the real world.

In Imperative programming, you write code that tell the computer what to do step by step to accomplish the goal. You use variables to store state and you can access this state a mutate it inside functions, loops, and conditional statements.

In contrast, a functional approach involves composing the problem as a set of functions to be executed. You define carefully the input to each function, and what each function returns. Then your program is essentially a composition of functions that describe the transformation of input data.

Here are some unique characteristics of FP :

  • There is no variables, but constants. The use of immutable data structures is strongly encouraged in FP
  • There is no explicit memory management (like in C for example). The garbage collector is responsible for this.
  • There are no non-local jumps and no exceptions.
  • There are no loops. Every time you’d need a loop in Imperative programming, you use recursion to reach your goal.
  • In pure Functional languages, there can’t be direct side-effects on peripherals. Monads are responsible for managing any side-effects. A Monad is a special type that wraps a value and abstracts the necessary side-effects for manipulating the external world.

Conclusion

Ok now it’s time for a break! 😊

This post gave us the basics so we can start coding in a functional way.

If you’re eager to learn more on functional programming, here are a few links that might be worth reading :

You can also have a look at my next post dealing with amazing Functional Programming Techniques for JavaScript 😉

If you have any suggestions or you think I missed something in that post, feel free to say it the comments 😊

Originally published on sparkyspace.com

--

--