1

I would like to know a way how to check if an object is of certain class, or derived from it. E.g.:

(defclass a nil
  nil)

(defclass b (a)
  nil)

(defparameter *foo* (make-instance 'b))

(my-function *foo* 'a) ; => t
(my-function *foo* 'b) ; => t

Alternatively, a function that returns list of all base classes for a given object (or class) would be also appreciated.

Mark Karpov
  • 7,499
  • 2
  • 27
  • 62
  • 1
    possible duplicate of [Equivalance of instanceof for CLOS? How to check if instance is inherited from another object?](http://stackoverflow.com/questions/19151569/equivalance-of-instanceof-for-clos-how-to-check-if-instance-is-inherited-from-a) – Lars Brinkhoff Jul 18 '14 at 18:23

2 Answers2

7

Use typep:

CL-USER 4 > (typep *foo* 'a)
T

CL-USER 5 > (typep *foo* 'b)
T
sds
  • 58,617
  • 29
  • 161
  • 278
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
0

You need to use MOP's (MetaObject Protocol) `class-direct-superclasses'

Quickload the library closer-mop and use `class-direct-superclasses' like so:

CL-USER> (closer-mop:class-direct-superclasses (find-class 'number))
(#<BUILT-IN-CLASS T>)
CL-USER>

If you have an instance of a class, you can do

CL-USER> (let ((table (make-instance 'test-table-2)))
           (class-direct-superclasses (class-of table)))
(#<STANDARD-CLASS STANDARD-OBJECT>)} 
CL-USER>

A possible gotcha (documented in the library): If you DEFPACKGE that :USEs closer-mop, instead of using CL, :USE closer-common-lisp

user1597986
  • 113
  • 4