Functional programming
Functional programming (FP) is a function-based paradigm of computer programming. The main idea is to decompose tasks into functions. In other words you are emphasis is on what is to be computed.
FP is focused on results, not the process. So it does not support iteration like loop statements and conditional statements like if-else. For example, in Kotlin there are high-order functions forEach() and takeIf().
Obviously language must support functional type to pass functions as arguments to other functions and to return values as functions.
Main principles of FP:
- immutability - you cannot change the value of a variable once assigned. If you need other value you create new one.
- avoid shared mutable state, ideally you should use pure functions
pure functions
A pure function is a function that:
- returns the same value for the same arguments
- has no side effects, i.e. no mutation of local static variables, non-local variables, mutable reference arguments or input/output streams.
For example, a function that calculates the area of a circle would be impure because it uses a global PI variable that might change.
fun circleArea(r: Float){
return r*r*PI
}
higher-order functions
A higher-order function is a function that takes functions as parameters, or returns a function.
Following kinds values of functional type may be used in language:
- lambdas - anonymous function that can be passed to the high-order function or may be its result
- callback - is any executable code that is passed as an argument to other code. Execution may be immediate as in a synchronous callback, or it might happen at a later as in an asynchronous callback.
- referrence - reference to the exist function or object method
For example, most languages with supporting FP have following high-order functions:
- filter() - expects a true or false value from callback to determine if the element should or should not be included in the result collection
- map() - transforms a collection by applying a function to all of its elements and building a new collection from the returned values
- reduce() - return a value created by combining the elements in collection, for example, sum of elements.
closures
A closure is a record storing a function together with an environment where that function was defined.
Environment here means a set of names like variables, functions, types and etc defined in a function's "surrounding context".
Let one function be defined inside another. Then the inner function can access the variables of the outer function, because the scope object and all its local variables tied with the internal function are saved. Closure will persist as long as inner function persists. As example, inner function can live after execution outer function.
Some languages have features which simulate the behavior of closures:
- C - via callbacks
- C++ - via function objects
- Objective-C - via blocks
- Java - via local classes and lambda functions