The Identity function
- functional
When you are not used to functional programming you may have seen that there is a function called
identity
which seems to be useless.
f(x) = x
Why would I use such a function?
In functional programming, functions are first-class citizens, which means that they can be passed as arguments and returned as value.
Once you start to read about it you will face some type of functions called high order functions (HOFs), which are functions that receives functions as arguments. This kind of functions improve its flexibility.
I'll use Javascript as a language to explain:
function sortBy(collection, function) {
// implementation
}
sortBy([{ name: 'Paul' }, { name: 'John' }], function(o) {
return o.name;
});
// => [{ name: 'John' }, { name: 'Paul' }]
Ok, sortBy
is nice when you have a collection of complex object, where you want to specify the
property to sort by. But, simple collections of numbers and strings, we don't need to pass this
function.
sortBy([3, 2, 1], identity);
// => [1, 2, 3]
So we could easily rewrite a sort
function that delegates to sortBy
, to avoid writting it every
time.
function sort(collection) {
return sortBy(collection, identity);
}
sort([3, 2, 1]);