# Function

## Contents

## Introduction

Functions are a theoretical concept. The simple idea is that a function is a *mapping* from the *domain* to the *range*. That is, the parameters it accepts (the domain) are translated to values it outputs (the range).

Think of a function as a black box with an input and an output. For every thing you put in, you get something out. For some kinds of input, the black box just fails altogether for one reason or another.

*Ideal* functions are exactly what the mathematical definition is. Given the same input, it will always produce the same output, whether that be some value in the range or an error due to input outside the domain.

Just like mathematically, when you say "a = 5", "a" will always be 5, but in computer programming languages, the definition of "a" can change, so too can functions change between invocations.

In computer programming, functions have:

- A signature or interface, meaning, what parameters are acceptable (the domain) and what it may produce (the range). The resulting value may also be an exception or error.
- A block of code that describes how the function works to the compiler.
- Usually, a new namespace created for every invokation, initialized to the values of the parameters passed in. (See scope.)

## Useful functions

These are functions that exist in many languages that are commonly useful. They may exist under different names in different languages.

### identity(x)

Returns "x" unchanged.

### apply(func, parameters...)

Given a function and parameters, invokes the function with the parameters and returns the results.

### partial_apply(func, parameters...)

Partially apply some parameters to a function, and return a *new* function that accepts the remaining parameters. Languages such as Haskell use this concept to build everything else.

### parse(string) -> syntax tree

Given a string, parse it into a syntax tree.

### compile(string) -> function (aka eval)

Given a string (in a particular programming language), compile it into a function that when called will execute the code.

### map(function, lists...)

Applies function to every item in the lists in parallel and returns a list of the results.

### ormap(function, lists...)

Like map, but stops iterating through the lists on the first non-false value and returns that value. If all values are false, then returns the last value.

### andmap(function, lists...)

Like map, but stops iterating on the first false value and returns it. Otherwise, it returns the last value.

### filter(function, lists...)

Like map, but instead of returning values that the function returns, it returns the items that the function returns "true" for.