词条 | Function object |
释义 |
In computer programming, a function object{{efn|1=In C++, a functionoid is an object that has one major method, and a functor is a special case of a functionoid.[1] They are similar to a function object, but not the same.}} is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax (a function parameter that can also be a function). Function objects are often called functors. DescriptionA typical use of a function object is in writing callback functions. A callback in procedural languages, such as C, may be performed by using function pointers.[2] However it can be difficult or awkward to pass a state into or out of the callback function. This restriction also inhibits more dynamic behavior of the function. A function object solves those problems since the function is really a façade for a full object, carrying its own state. Many modern (and some older) languages, e.g. C++, Eiffel, Groovy, Lisp, Smalltalk, Perl, PHP, Python, Ruby, Scala, and many others, support first-class function objects and may even make significant use of them.[3] Functional programming languages additionally support closures, i.e. first-class functions that can 'close over' variables in their surrounding environment at creation time. During compilation, a transformation known as lambda lifting converts the closures into function objects. In C and C++Consider the example of a sorting routine that uses a callback function to define an ordering relation between a pair of items. A C program using function pointers may appear as: In C++, a function object may be used instead of an ordinary function by defining a class that overloads the function call operator by defining an Notice that the syntax for providing the callback to the In C++11, the lambda expression provides a more succinct way to do the same thing. It is possible to use function objects in situations other than as callback functions. In this case, the shortened term functor is normally not used about the function object. Continuing the example, In addition to class type functors, other kinds of function objects are also possible in C++. They can take advantage of C++'s member-pointer or template facilities. The expressiveness of templates allows some functional programming techniques to be used, such as defining function objects in terms of other function objects (like function composition). Much of the C++ Standard Template Library (STL) makes heavy use of template-based function objects. Maintaining stateAnother advantage of function objects is their ability to maintain a state that affects In C#In C#, function objects are declared via delegates. A delegate can be declared using a named method or a lambda expression. Here is an example using a named method. Here is an example using a lambda expression. In DD provides several ways to declare function objects: Lisp/Python-style via closures or C#-style via delegates, respectively: The difference between a delegate and a closure in D is automatically and conservatively determined by the compiler. D also supports function literals, that allow a lambda-style definition: To allow the compiler to inline the code (see above), function objects can also be specified C++-style via operator overloading: In EiffelIn the Eiffel software development method and language, operations and objects are seen always as separate concepts. However, the agent mechanism facilitates the modeling of operations as runtime objects. Agents satisfy the range of application attributed to function objects, such as being passed as arguments in procedural calls or specified as callback routines. The design of the agent mechanism in Eiffel attempts to reflect the object-oriented nature of the method and language. An agent is an object that generally is a direct instance of one of the two library classes, which model the two types of routines in Eiffel: Within software text, the language keyword The routine In other library classes, agents are seen to be used for different purposes. In a library supporting data structures, for example, a class modeling linear structures effects universal quantification with a function When agents are created, the arguments to the routines they model and even the target object to which they are applied can be either closed or left open. Closed arguments and targets are given values at agent creation time. The assignment of values for open arguments and targets is deferred until some point after the agent is created. The routine When the target of an agent is left open, the class name of the expected target, enclosed in braces, is substituted for an object reference as shown in the text The ability to close or leave open targets and arguments is intended to improve the flexibility of the agent mechanism. Consider a class that contains the following procedure to print a string on standard output after a new line: The following snippet, assumed to be in the same class, uses This example uses the procedure The sequence of three instructions prints the strings in Procedure Open and closed arguments and targets also allow the use of routines that call for more arguments than are required by closing all but the necessary number of arguments: The Eiffel agent mechanism is detailed in the Eiffel ISO/ECMA standard document. In JavaJava has no first-class functions, so function objects are usually expressed by an interface with a single method (most commonly the For an example from Java's standard library, In Java 8+, this can be written as: In JavaScriptIn JavaScript, functions are first class objects. JavaScript also supports closures. Compare the following with the subsequent Python example. An example of this in use: In JuliaIn Julia, methods are associated with types, so it is possible to make any arbitrary Julia object "callable" by adding methods to its type. (Such "callable" objects are sometimes called "functors.") An example is this accumulator mutable struct (based on Paul Graham's study on programming language syntax and clarity):[4] Such an accumulator can also be implemented using closure: In Lisp and SchemeIn Lisp family languages such as Common Lisp, Scheme, and others, functions are objects, just like strings, vectors, lists, and numbers. A closure-constructing operator creates a function object from a part of the program: the part of code given as an argument to the operator is part of the function, and so is the lexical environment: the bindings of the lexically visible variables are captured and stored in the function object, which is more commonly called a closure. The captured bindings play the role of member variables, and the code part of the closure plays the role of the anonymous member function, just like operator () in C++. The closure constructor has the syntax Many uses of functors in languages like C++ are simply emulations of the missing closure constructor. Since the programmer cannot directly construct a closure, they must define a class that has all of the necessary state variables, and also a member function. Then, construct an instance of that class instead, ensuring that all the member variables are initialized through its constructor. The values are derived precisely from those local variables that ought to be captured directly by a closure. A function-object using the class system, no use of closures: Since there is no standard way to make funcallable objects in Lisp, we fake it by defining a generic function called FUNCTOR-CALL. This can be specialized for any class whatsoever. The standard FUNCALL function is not generic; it only takes function objects. It is this FUNCTOR-CALL generic function that gives us function objects, which are a computer programming construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. We have almost the same syntax: FUNCTOR-CALL instead of FUNCALL. Some Lisps provide funcallable objects as a simple extension. Making objects callable using the same syntax as functions is a fairly trivial business. Making a function call operator work with different kinds of function things, whether they be class objects or closures is no more complicated than making a + operator that works with different kinds of numbers, such as integers, reals or complex numbers. Now, a counter implemented using a closure. This is much more brief and direct. The INITIAL-VALUE argument of the MAKE-COUNTER factory function is captured and used directly. It does not have to be copied into some auxiliary class object through a constructor. It is the counter. An auxiliary object is created, but that happens behind the scenes. Scheme makes closures even simpler, and Scheme code tends to use such higher-order programming somewhat more idiomatically. More than one closure can be created in the same lexical environment. A vector of closures, each implementing a specific kind of operation, can quite faithfully emulate an object that has a set of virtual operations. That type of single dispatch object-oriented programming can be done fully with closures. Thus there exists a kind of tunnel being dug from both sides of the proverbial mountain. Programmers in OOP languages discover function objects by restricting objects to have one main function to do that object's functional purpose, and even eliminate its name so that it looks like the object is being called! While programmers who use closures are not surprised that an object is called like a function, they discover that multiple closures sharing the same environment can provide a complete set of abstract operations like a virtual table for single dispatch type OOP. In Objective-CIn Objective-C, a function object can be created from the An advantage of In PerlIn Perl, a function object can be created either from a class's constructor returning a function closed over the object's instance data, blessed into the class: or by overloading the &{} operator so that the object can be used as a function: In both cases the function object can be used either using the dereferencing arrow syntax $ref->(@arguments): or using the coderef dereferencing syntax &$ref(@arguments): In PHPPHP 5.3+ has first-class functions that can be used e.g. as parameter to the usort() function: It is also possible in PHP 5.3+ to make objects invokable by adding a magic __invoke() method to their class:[5] In PowerShellIn the Windows PowerShell language, a script block is a collection of statements or expressions that can be used as a single unit. A script block can accept arguments and return values. A script block is an instance of a Microsoft .NET Framework type System.Management.Automation.ScriptBlock. In PythonIn Python, functions are first-class objects, just like strings, numbers, lists etc. This feature eliminates the need to write a function object in many cases. Any object with a An example is this accumulator class (based on Paul Graham's study on programming language syntax and clarity):[6] An example of this in use (using the interactive interpreter): Since functions are objects, they can also be defined locally, given attributes, and returned by other functions ,[7] as demonstrated in the following example: In RubyIn Ruby, several objects can be considered function objects, in particular Method and Proc objects. Ruby also has two kinds of objects that can be thought of as semi-function objects: UnboundMethod and block. UnboundMethods must first be bound to an object (thus becoming a Method) before they can be used as a function object. Blocks can be called like function objects, but to be used in any other capacity as an object (e.g. passed as an argument) they must first be converted to a Proc. More recently, symbols (accessed via the literal unary indicator Now, method Because of the variety of forms, the term Functor is not generally used in Ruby to mean a Function object. Just a type of dispatch delegation introduced by the [https://web.archive.org/web/20070107205748/http://facets.rubyforge.org/ Ruby Facets] project is named as Functor. The most basic definition of which is: This usage is more akin to that used by functional programming languages, like ML, and the original mathematical terminology. Other meaningsIn a more theoretical context a function object may be considered to be any instance of the class of functions, especially in languages such as Common Lisp in which functions are first-class objects. The ML family of functional programming languages uses the term functor to represent a mapping from modules to modules, or from types to types and is a technique for reusing code. Functors used in this manner are analogous to the original mathematical meaning of functor in category theory, or to the use of generic programming in C++, Java or Ada. In Haskell, the term is used in the same sense as in category theory. In Prolog and related languages, functor is a synonym for function symbol. See also
Notes{{notelist}}References1. ^[https://isocpp.org/wiki/faq/pointers-to-members#functor-vs-functionoid What's the difference between a functionoid and a functor?] 2. ^{{cite web | url = http://progtutorials.tripod.com/cpp1.htm#_Toc50820124 | title = C++ Tutorial Part I - Basic: 5.10 Function pointers are mainly used to achieve call back technique, which will be discussed right after. | author = Silan Liu | authorlink = | date = | publisher = TRIPOD: Programming Tutorials Copyright © Silan Liu 2002 | quote = Function pointers are mainly used to achieve call back technique, which will be discussed right after. | accessdate = 2012-09-07}} 3. ^{{cite web | url = http://progtutorials.tripod.com/cpp1.htm#_Toc50820124 | title = C++ Tutorial Part I - Basic: 5.10 Function pointers are mainly used to achieve call back technique, which will be discussed right after. | author = Paweł Turlejski | authorlink = | date = 2009-10-02 | publisher = Just a Few Lines | quote = PHP 5.3, along with many other features, introduced closures. So now we can finally do all the cool stuff that Ruby / Groovy / Scala / any_modern_language guys can do, right? Well, we can, but we probably won’t… Here's why. | accessdate = 2012-09-07}} 4. ^Accumulator Generator 5. ^PHP Documentation on Magic Methods 6. ^Accumulator Generator 7. ^[https://docs.python.org/3/reference/compound_stmts.html#function-definitions Python reference manual - Function definitions] Further reading
External links
8 : Object (computer science)|Subroutines|Articles with example C code|Articles with example C++ code|Articles with example Java code|Articles with example Perl code|Articles with example Python code|Articles with example Ruby code |
随便看 |
|
开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。