Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class introspection in Common Lisp

Java's java.lang.Class class has a getDeclaredFields method which will return all the fields in a given class. Is there something similar for Common Lisp? I came across some helpful functions such as describe, inspect and symbol-plist after reading trying out the instructions in Successful Lisp, Chapter 10 (http://www.psg.com/~dlamkins/sl/chapter10.html). But none of them do what getDeclaredFields does.

like image 506
Bala Avatar asked Apr 12 '09 18:04

Bala


People also ask

What is exp in Lisp?

exp and expt perform exponentiation. exp returns e raised to the power number, where e is the base of the natural logarithms.

What does Common Lisp provide?

Common Lisp is extensible through standard features such as Lisp macros (code transformations) and reader macros (input parsers for characters). Common Lisp provides partial backwards compatibility with Maclisp and John McCarthy's original Lisp. This allows older Lisp software to be ported to Common Lisp.

Is clojure better than Common Lisp?

Common lisp comparatively faster than Clojure as it uses compilers like SBCL which makes common lisp faster than C programming or any other low-level programming language and it also provides a variety of different libraries for different concepts that can be included in the program for easy execution.

Does Lisp support OOP?

Lisp is an object-oriented language, yes, but not because it has adopted the object-oriented model. Rather, that model turns out to be just one more permutation of the abstractions underlying Lisp. And to prove it we have CLOS, a program written in Lisp, which makes Lisp an object-oriented language.


2 Answers

You should use class-slots and/or class-direct-slots (both are from CLOS Metaobject Protocol, MOP). class-slots returns all slots that are present in given class, and class-direct-slots returns all slots are declared in class definition.

Different lisp implementations implement MOP slightly differently; use closer-mop package to have uniform interface to MOP.

Example:

(defclass foo ()
  (foo-x))

(finalize-inheritance (find-class 'foo)) ;this is needed to be able to query class slots and other properties. Or, class is automatically finalized when its first instance is created

(class-slots (find-class 'foo))
=> (#<STANDARD-EFFECTIVE-SLOT-DEFINITION FOO-X>)

(slot-definition-name (first (class-slots (find-class 'foo))))
=> FOO-X

Example :

(defun inspect (( object standard-object))
  (inspect-rec (class-slots (class-of object)) object) )


(defun inspect-rec (slots o)
  ( if(atom slots) ()
   (let ((sn (slot-definition-name (car slots)))) (cons (list sn '=> ( slot-value o sn) )  ( inspect-rec (cdr slots) o)))))
like image 77
dmitry_vk Avatar answered Nov 09 '22 11:11

dmitry_vk


I think you're looking for the MetaObject Protocol for CL.

like image 30
JP Alioto Avatar answered Nov 09 '22 12:11

JP Alioto