Basics of Functional Programming

Functional programming is a programming paradigm characterized by the composition of pure functions as the primary means of expression.

  1. Functional programming - what is a function?
  2. Programming - what is programming?
  3. Use of functions - what does function usage look like?
  4. Composition - what is function composition?
  5. Pure functions - what is function purity?

What is a function?

Within the context of functional programming, there are two types of functions. The first is a total function. A total function is a function that is defined for all of its possible inputs. In other words, every input value has a corresponding output value.

The second type of function is a partial function. A partial function is a function that is not defined for all of its possible inputs.

Function Totality / Partiality

The core definition of "function" is fundamentally abstract. This means it can apply to many different instances of functions. The following example is one such instance:

Domain

The domain of a function is the set of all possible input values for the function.

Example Domain: (a, b, c)

  • a
  • b
  • c

Codomain

The codomain of a function is the set of all possible output values for the function.

Example Codomain: (1, 2, 3)

  • 1
  • 2
  • 3

Function

A function is a mapping from a domain to a codomain. This mapping can be expressed in numerous different ways, some of which are more visual and intuitive than others.

Example Function: ((a, 1), (b, 2), (c, 3))

  • a → 1
  • b → 2
  • c → 3

A function can be expressed in a programming language by a function declaration. This usually includes a function name, a list of parameters, and a body. In a typed programming language, this can also include a type signature.

For example, in TypeScript, a function declaration looks like this:

function add(a, b) {
            return a + b;
          }