Generic function
≈ 1 min read
Names in other languages
No names in other languages are held for this entry yet.
Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.
In computer programming, a generic function is a function defined for polymorphism.
Impact
In computer programming, a generic function is a function defined for polymorphism. (send object :message) With New Flavors, it was decided the message should be a real function and the usual function calling syntax should be used: (message object) 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.
How it works
(defgeneric collide (object-1 object-2)) 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 (first parameter object-1) and spaceship (second parameter object-2). The parameters are used as normal variables inside the method body. There is no special namespace that has access to class slots.
(defmethod collide ((object-1 asteroid) (object-2 spaceship)) (format t "asteroid ~a collides with spaceship ~a" object-1 object-2)) Calling the generic function: ? (collide (make-instance 'asteroid) (make-instance 'spaceship)) 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. ? (find-method #'collide nil (list (find-class 'asteroid) (find-class 'spaceship)))
Text derived from https://en.wikipedia.org/w/index.php?oldid=1281442317 under CC BY-SA 4.0; modifications have been made.