e01.org

Generic function

In computer programming, a generic function is a function defined for polymorphism.

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. (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)))

source: e01 Encyclopedia · licence: CC BY-SA 4.0 · page · source revision

Cite this

"Generic function". 1742468520. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1281442317

JSON record · API collection · citation policy