First-Class Functions

First-class functions can either accept another function as an argument or return a function. Being able to create functions and return them or pass them
to other functions becomes extremely useful in code
reusability and code
abstractions.


What are first-class functions?

First-class functions are functions treated as objects themselves, meaning we can pass a function as a parameter to another function, return a function from a function, or store a function in a variable.

Pure functions are one of the most useful features in functional programming, as well as one of the more difficult concepts to learn and use effectively.

What is a function?

In its most generalized form, a function is merely a way to encapsulate a piece of work so that we can easily reference

it again.

What are the components of a function?

Name - used to identify the function
Parameter List - containing objects to operate on
Body - where we transform the parameters and execute some logic
Return - to specify the result

Functions as an object


Function: {
name: 'add',
args: numeric,
body: sum = numeric + 1
return: sum
}

A pre-condition confirms that the args passed in are of a specific type.

For example, we could enforce our numeric arg to be an integer like so before we execute the call.

function addOne(numeric) {
if (typeof numeric !== 'integer') {
throw new Error(`Type ${typeof numeric} is invalid. Parameter must Must be an Integer`)
}

let sum = numeric + 1

return numeric
}

We have created a pre-condition on our function. The condition that needs to be met previous to our function running is that the numeric arg must be of the Integer type.


A concise way to add a pre-condition is to use type checking on the function input.
(given your language allows it typescript, Java, C++, etc...).

function addOne(integer numeric) {
let sum = numeric + 1

return numeric
}

This removes the need to add your own condition and executes before the function runs.


A post-condition is used directly after your function body runs and is used to conditionally check the given return from your function is of the right type.


function addOne(numeric) {
let sum = numeric + 1

/** Post Condition **/
if (typeof sum !==
'integer') {
throw new Error(`addOne must return an integer type`)
}


return
sum
}

A concise way to add a post-condition is to use type checking on the return value of your function. (for languages that allow it - typescript, PHP, Java, etc...)


function addOne (numeric) : integer {
return numeric + 1
}



Adding preconditions and post
-conditions together, we can confirm the input and the output are of the given types we what we expect.

function addOne (integer numeric) : integer {
return numeric + 1
}