Function

In mathematics, a function from a set $X$ to a set $Y$ assigns to each element of $X$ exactly one element of $Y$. The set $X$ is called the domain of the function and the set $Y$ is called the codomain of the function.

In computer programming, a function is, in general, a piece of a computer program which implements the abstract concept of function. That is, it is a program unit that produces an output for each input.

However, in many programming languages every subroutine is called a function, even when there is no output, and when the functionality consists simply of modifying some data in the computer memory.

Functional programming is the programming paradigm consisting of building programs by using only subroutines that behave like mathematical functions. For example, if_then_else is a function that takes three functions as arguments, and, depending on the result of the first function (true or false), returns the result of either the second or the third function.

Once a programmer defines a function, they can then call it whenever they need it, simply using its name. Additionally, in order to work, thefunction will probably require some inputs or parameters, which are given to the function each time it is called.

For example, a usage of the function print in Python:

Untitled

The print function, used to display messages on the screen, is called by giving the name of the function, print, followed by a pair of parentheses (brackets) which contain the parameters you want to pass to it. In this case, the string "hello world" is the only parameter. Functions can be thought of as little machines that perform a specific task, where the parameters are the inputs to the machine.

In Java, methods have names. Calling methods uses their name. In Java, methods and fields are different from each other.

public int foo = 10;
public int bar(int nr) {
    return nr + 1;
}

In JavaScript we have the same:

var foo = 10;
function bar(int nr) {
    return nr + 1;
}

but also:

var bar = function(int nr) {
    return nr + 1;
}

Scala can do the same:

val foo = 10;
def bar(nr: Int): Int = {
    return nr + 1;
}

but also:

val bar = (nr: Int) => {
    nr + 1
}