Re: method-let



nallen05@xxxxxxxxx writes:

Has anyone ever seen something implimented like a METHOD-LET operator,
that defines a method for a generic function but only within the scope
of it's form, like FLET for methods?

(defclass wheat ())

(defclass bread (wheat) ())

(defclass toast (bread) ())

(defgeneric eat (x))

(defmethod eat ((x wheat))
(print "yuck"))

(defmethod eat ((x toast))
(print "yum"))

(method-let ((foo ((x bread))
(print "will you put this in the toaster?")))
(mapc #'foo (list (make-instance 'wheat)
(make-instance 'bread)
(make-instance 'toast))))
=>
"yuck"
"will you put this in the toaster?"
"yum"
NIL


You can do it with a normal flet:

C/USER[615]> (flet ((eat (x)
(if (eq (class-of x) (find-class 'bread))
(print "will you put this in the toaster?")
(eat x))))
(mapc (function eat) (list (make-instance 'wheat)
(make-instance 'bread)
(make-instance 'toast)))
(values))

"yuck"
"will you put this in the toaster?"
"yum"


I think this would be super usefull for say... making PRINT-OBJECT
behave differently in different situations (like printing to XML or in
a GUI) but not losing the semactics of the type-hierarchy and the
method dispatch...

This is not a good idea. PRINT-OBJECT, being a standard method has
some restrictions that may become unfortunate. For example, it's not
necessarily called when specialized on a standard type or standard
class.

Note that:

"The function print-object is called by the Lisp printer; it
should not be called by the user."

-- http://www.lispworks.com/documentation/HyperSpec/Body/f_pr_obj.htm


If you want to format differently depending on the "device", you
should use your own generic function:

(defgeneric render (object device))

(defmethod render ((object integer) (device xml-device))
(format (device-stream device) "<integer>~D</integer>" object))

(defmethod render ((object date) (device text-device))
(format (device-stream device) "~4,'0D-~2,'0D-~2,'0D"
(year date) (month date) (day date)))

....

--
__Pascal Bourguignon__ http://www.informatimago.com/
.