Skip to content
CLOS — Classes and Generic Functions
step 1/5

Reading — step 1 of 5

Learn

~1 min readConditions and CLOS

CLOS (Common Lisp Object System) is the most flexible OO system in any major language. It separates classes (data) from methods (behavior).

Defining a class:

(defclass person ()
    ((name :initarg :name :accessor person-name)
     (age :initarg :age :accessor person-age :initform 0)))
  • :initarg — keyword for the constructor
  • :accessor — generates getter/setter
  • :initform — default value

Creating instances:

(defparameter *ada* (make-instance 'person :name "Ada" :age 36))
(person-name *ada*)            ; "Ada"
(setf (person-age *ada*) 37)

Generic functions with multiple methods:

(defgeneric greet (entity))

(defmethod greet ((p person))
    (format nil "Hi, ~a" (person-name p)))

(defmethod greet ((s string))
    (format nil "Hello, string ~s" s))

(defmethod greet (anything)        ; fallback for any type
    (format nil "unknown: ~a" anything))

Multi-method dispatch — methods can specialize on multiple arguments:

(defgeneric combine (a b))

(defmethod combine ((a number) (b number)) (+ a b))
(defmethod combine ((a string) (b string)) (concatenate 'string a b))
(defmethod combine ((a list) (b list)) (append a b))

Method selection looks at ALL arguments' types — not just the first. CLOS's most distinctive feature.

Inheritance with :before, :after, :around qualifiers:

(defmethod greet :before ((p person))
    (format t "about to greet~%"))

(defmethod greet :after ((p person))
    (format t "greeted~%"))

These run automatically before/after the main method. Used heavily in Lisp libraries.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…