In some systems for object-oriented programming such as the Common LispObject System and Dylan, a generic function is an entity made up of all methods having the same name. Typically a generic function is an instance of a class that inherits both from function and standard-object. Thus generic functions are both functions and ordinary objects. The book The Art of the Metaobject Protocolexplains the implementation and use of CLOS generic functions in detail. One of the early object-oriented programming extensions to Lisp is Flavors. It used the usual message sending paradigm influenced by Smalltalk. The Flavors syntax to send a message is:
With New Flavors, it was decided the message should be a real function and the usual function calling syntax should be used:
message now is a generic function, an object and function in its own right. Individual implementations of the message are called methods. The same idea was implemented in CommonLoops. New Flavors and CommonLoops were the main influence for the Common Lisp Object System.
Example
Common Lisp
Define a generic function with two parameters object-1 and object-2. The name of the generic function is collide.
Methods belonging to the generic function are defined outside of classes. Here we define a method for the generic function collide which is specialized for the classes asteroid and spaceship. The parameters are used as normal variables inside the method body. There is no special namespace that has access to class slots. ) )
Calling the generic function: ? ) asteroid # collides with spaceship #
Common Lisp can also retrieve individual methods from the generic function. FIND-METHOD finds the method from the generic function collide specialized for the classes asteroid and spaceship. ? ))
Comparison to other languages
Generic functions correspond roughly to what Smalltalk terms methods, with the notable exception that, in Smalltalk, the receiver's class is the sole determinant of which body of code is called: the types or values of the arguments are irrelevant. In a programming language with multiple dispatch when a generic function is called, method dispatch occurs on the basis of all arguments, not just one which is privileged. New Flavors also provided generic functions, but only single dispatch.