Tuesday, June 11, 2013

Functional Programming

What is it?

Functional programming is a programming paradigm. It is a style of building the structures and elements of computer programs.

How it works?

Treat computation as the evaluation of mathematical functions. Functions can be chained, passed as parameters to other functions, and higher order functions can be composed from other functions.

Immutable

Functions avoid changing-state. They take in input and return out without changing input or any other global state.

Declarative

Functions are declarative. Function signature states what it needs for input and is clear about it returns. How the action is actually performed is encapsulated by the function and is of really interest to the user of the function.

Pure

Functions don't depend on any data other than what is passed in, and don't alter data other than what they returned. Return the same result for the parameter passed in.

// Not pure because the return value is different based on today's date
function daysTil(Date targetDate){
  // returns days til targetDate from now
}

// Pure because the return value is always the same regardless of today's date
function daysTil(Date targetDate, Date nowDate){
  // returns days til targetDate from nowDate
}

Characteristics

  • Functional programming is inspired by Lambda calculus
  • Functions are first-class citizens
  • Functions can be assigned to variables
  • Functions can be passed to other functions
  • Functions can be returned from other functions
  • Functions can accept other functions as arguments; the function accepting the argument is called a higher-order function
  • Data is typically immutable, therefore, concurrent threads can access data without locking
  • Pure functions are functions that always return the same result when same arguments are passed in
  • Pure function have no side-effects i.e. they do not change any global state such as performing I/O
  • Pure function can be executed over and over without affecting the global state
  • Pure function, due to their very nature of not having side-effects, are well-suited for concurrent execution of code