| FazBrowse Wikipedia Viewer | Main Page | | |
| Viewing: https://en.wikipedia.org/wiki/Generic_function |
| Polymorphism | |
|---|---|
| Ad hoc polymorphism | |
| Parametric polymorphism | |
| Subtyping | |
| (sendobject:message)
With New Flavors, it was decided the message should be a real function and the usual function calling syntax should be used: (defmethodcollide((object-1asteroid)(object-2spaceship))
(formatt"asteroid ~a collides with spaceship ~a"object-1object-2))
Calling the generic function: collides with spaceship #<SPACESHIP 40200048CB>\n"}}'>?(collide(make-instance'asteroid)(make-instance'spaceship))
asteroid#<ASTEROID4020003FD3>collideswithspaceship#<SPACESHIP40200048CB>
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. \n"}}'>?(find-method#'collidenil(list(find-class'asteroid)(find-class'spaceship)))
#<STANDARD-METHODCOLLIDENIL(ASTEROIDSPACESHIP)4150015E43>
Comparison to other languageseditGeneric 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 (single dispatch). 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. In JavaScript, a generic function is a function that can work with values of different types, rather than a specific type. This is achieved through the use of type parameters or by dynamically checking the type of the value being operated on. One common use case for generic functions in JavaScript is to create reusable functions that can work with different data types, such as arrays, strings, or objects. JavaScript's dynamic typing system makes it particularly suited for the creation of generic functions, as values can be easily coerced or converted to different types as needed. Referencesedit
|