Functions

A function is a binary relation between 2 sets (ie. collection of values). The input set is mapped to a return value.

A function's type consists of the types of its argument and its return type.

  • ie. function type === function signature

the indent level of a function should not be greater than one or two.

  • If a function does only those steps that are one level below the stated name of the function, then the function is doing one thing.

Functions can be either total or partial.

  • A total function is one that will succeed for all possible inputs, whereas a partial function may not.
/* No matter what numbers you specify, this function will always return a value. You can be confident that under no circumstances
 * will your program crash because of this function (Reality is slightly more complex, but this is close enough)
 * As such, this function is a total function.
 */
function add( x, y ){ return x + y };

// All numbers can be converted to strings, so this is a total function.
function numberToString( num ) { return num.toString() };

When a function is called, its memory is allocated on the stack.

  • When a function executes, it adds its state data to the top of the stack; when the function exits this data is removed from the stack.
    • All data, such as local variables, parameters, return address etc. are included in this single unit that is added to the stack.

Memory allocation of recursive functions

A recursive function calls itself, therefore, the memory for a called function is allocated on top of memory allocated for calling function.

  • a different copy of local variables is created for each function call. When the base case is reached, the child function returns its value to the function from which it was called. Then, this child function’s stack frame is removed. This process continues until the parent function is returned.

If the memory stack was a stack of plates, then each execution of the function would be a plate added to the stack. Plates would continue to be added until the base case was reached. At that point, the top plate would be removed, and its return value would go to the next plate. This would continue until the return value reaches the final plate in the stack, which would return the final value to the initial calling site.

Function composition

Intuitively, composing functions is a chaining process in which the output of function f feeds the input of function g.

Higher-order function

A higher-order function is such a function that:

  • Has a parameter that has a function type, OR
  • it’s return type is a function type

Children
  1. First-Class Function
  2. Function Best Practices

Backlinks