What’s the difference between a function and a functor?
What's the difference between a function and a functor?
These instruction constitute a unit which can be used in any part of the program where that task needs to be performed. (Read Straight From the Programming Experts: What Functional Programming Language is Best to Learn Now?)
The function will provide a result value that depends on its parameters and arguments, such as computing mathematical values to determine an output. The function can also include performing certain tasks depending on the result, such as modifying data inside a database or start other linked functions in a recursively manner.
In procedural programming (PP), functions, procedures or subroutines perform operations on the data. In this top-down approach, computers receive instructions in the form of functions to know what to do, step by step, to carry out any task.
In OOP, data and functions (and, therefore, computer behaviors) are encapsulated into objects. Functions are not something on their own anymore, but they are always connected to objects in a modular fashion.
Each object "knows" how to perform its tasks and interact with the other objects that constitute the application itself.
Functors are objects that behave as functions. They are class objects which can overload the function operator() and act as function themselves. They can encapsulate their own function which is executed when needed.
Pointers to member functions or arbitrary classes can be built up so they are all called through the same interface regardless of their class.
For example: Let's suppose we got a truck driver (our object) and that we want them to reach a certain location. In PP you must hand them a book with instructions on how to drive (a function), while in OOP this "knowledge" is already part of the object itself.
So these instructions determine the speed that the truck must keep on certain roads, say 55 mph on city roads, 65 mph on motorways and 70mph on highways. Now let's imagine that one day we got a urgent delivery, and we we want him to increase his speed by 15 mph. In PP, we must write several different functions to modify each speed.
In OOP, instead, we only need a functor to increment them all by 15 mph since the object is a class that was created to overload the operator().
More Q&As from our experts
- Why should we care about Natural Language Disambiguation?
- How can I learn big data analytics?
- How can IT security be measured?
- Programming Language
- Procedural Programming
- Object-Oriented Programming
- Object-Oriented Interface
- Object-Oriented Database
Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.