Page 1 of 1

Create a method dynamically for an instance of a class

Posted: Thu Mar 01, 2012 12:12 pm
by jecxjo
I'm new to Lisp, still trying to grasp the full usage of macros so bare with me if I'm doing this wrong.

I want to create a class (lets call it foo) that has a method that allows you to create a method using a passed in name, and object to manipulate contained in the instance of the class. For example:

Code: Select all

(defclass foo ()
  ((objects :initform '() :accessor list-objects)))

(defparameter inst-1 (make-instance 'foo))
(defparameter inst-2 (make-instance 'foo))

(defparameter x 1)
(defparameter y 2)

(add-method-to-foo inst-1 'print-number x (lambda (z) (print z)))

(add-method-to-foo inst-2 'print-number y (lambda (z) (format t "printing number ~d~%" z)))

(print-number inst-1)
=> 1
(print-number inst-2)
=> "printing number 2"

(list-objects inst-1)
=> (x)
(list-objects inst-2)
=> (y)
As fields in the class are added (at run time) I'd be able to define methods that are connected with the instance of the object. If you were to create a new instance of the class it would have a whole new list of objects with a whole new list of methods.

Re: Create a method dynamically for an instance of a class

Posted: Thu Mar 01, 2012 11:08 pm
by ramarren
You might be interested in a prototype based object language extension such as Sheeple.

Generally, adding function/methods at runtime is not the right thing, since if you are writing code calling them then you can just define them in the source and make them available at compile time, and if you are calling them by some other method then they do not have to be named top-level methods. You would just put lambdas in either slots of instances or a hash-table in a single slot, if you want a dynamic method list, and funcall them after retrieving them from there.

Re: Create a method dynamically for an instance of a class

Posted: Fri Mar 02, 2012 3:14 am
by gugamilare
If you want to define methods at run-time, you can use MOP (Metaobject Protocol) via closer-mop.

Re: Create a method dynamically for an instance of a class

Posted: Fri Mar 02, 2012 3:20 am
by Kompottkin
Sheeple is fun.

In case you happen to be using Clozure CL, you might want to use my fork, which contains a Clozure CL 1.7 workaround that hasn't yet been merged into mainline.

Alternatively, execute

Code: Select all

(setq cl:*print-pprint-dispatch* (copy-pprint-dispatch nil))
before loading Sheeple.

Re: Create a method dynamically for an instance of a class

Posted: Mon Jun 18, 2012 9:58 pm
by Adlai
Upstream CCL has fixed the problem with pprint tables in CCL 1.8, so that shouldn't be a problem...

If you're still on CCL 1.7, that shouldn't be a problem either, as I've (finally) merged in the patch.

</shamelessPlug>