Search code examples
common-lispsbclclos

What' the meaning of method-generic-function?


I'm learning common-lisp and CLOS.

I started with the tutorial from http://cl-cookbook.sourceforge.net/clos-tutorial/

In Section 4.3, it mentioned that

A generic function is a lisp function which is associated with a set of methods and dispatches them when it's invoked.

It also present two functions generic-function-methods and method-generic-function:

CL-USER 63 > #'my-describe
#<STANDARD-GENERIC-FUNCTION MY-DESCRIBE 21111C2A>

CL-USER 64 > (generic-function-methods #'my-describe)
(#<STANDARD-METHOD MY-DESCRIBE NIL (T) 2110B544>
 #<STANDARD-METHOD MY-DESCRIBE NIL (ANIMAL) 21111BF4>)

CL-USER 65 > (method-generic-function (car *))
#<STANDARD-GENERIC-FUNCTION MY-DESCRIBE 21111C2A>

I can understand the 1st one (i.e. generic-function-methods), it tells me the set of methods in the generic function my-describe.

But what about the 2nd one (i.e. (method-generic-function (car *)))?

I don't quite understand it.

PS: I tried to use this function in REPL, but failed:

CL-USER> #'method-generic-function

undefined.
   [Condition of type UNDEFINED-FUNCTION]

My environment is SBCL + quicklisp + slime.

Can I use this function in SBCL?

Thanks.


Update:

I seem to understand the meaning of method-generic-function:

It just return the generic-function from the particular method #<STANDARD-METHOD MY-DESCRIBE NIL (T) 2110B544>.

The confusing thing is the * in (car *), it seems return the value of the last expression.


Solution

    • Method-generic-function gives you the generic function that the given method is associated with.
    • Method-generic-function is not imported into the cl-user package in SBCL. You will find it in sb-mop (so, sb-mop:method-generic-function). The MOP is not entirely incorporated in the Common Lisp standard.
    • For portable use of the entire MOP, use the library “Closer to MOP” (closer-mop).
    • In the REPL, * refers to the first return value of the last evaluated expression. In your case, that was the list of methods returned by generic-function-methods. So you see that these two are more or less inverse functions in this one-to-many relation.