The things we call functions in C++ or any other imperative language, are not the same things mathematicians call functions. A mathematical function is just a mapping of values to values.
- One good definition of a function is a relation between two sets, the domain and co-domain, such that each value in the domain corresponds to exactly one value in the co-domain.
- One consequence of this definition is that functions cannot change state; in fact, a system cannot have a state. Most programming is stateful, because state is exceptionally convenient.
*Pure *functional programming works with values, functions and expressions while those expressions are pure, meaning they only compute values and do not “do” anything besides computing values. This is also called Referential Transparency.
A **pure function **is one without any side-effects.
A side-effect really means that the function keeps some sort of hidden state inside it.
**strlen**** is a good example of a pure function in C. If you call**strlen****with the same string, it always returns the same length.- The output of
**strlen**** **(the length) only depends on the inputs (the string) and nothing else.
- The output of
- Many functions in C are, unfortunately, impure. For example,
**malloc**- If you call it with the same number, it certainly won’t return the same pointer to you.
**malloc**, of course, relies on a huge amount of hidden internal state (objects allocated on the heap, the allocation method in use, grabbing pages from the operating system, etc.).
- If you call it with the same number, it certainly won’t return the same pointer to you.
SPOILER: Later we’ll see how monads let us model all kinds of effects using only pure functions. So we really don’t lose anything by restricting ourselves to mathematical functions.
There are various theoretical advantages of having pure functions. One advantage is that ==if a function is pure, then if it is called several times with the same arguments, the compiler only needs to actually call the function once==.
https://blog.kubukoz.com/what-makes-a-function-pure/