Mixins in Common Lisp

Part 1: Creating a Fundamental Class

(defclass fundamental-test ()
((test-form :initarg :form
:accessor test-form)
(test-value :initarg :value
:accessor test-value)
(test-result :initform nil
:accessor test-result)
(test-equal :initform #'equal
:initarg :test
:accessor test-equal)))
(defgeneric run-test (obj))(defmethod run-test ((obj fundamental-test))
(if (funcall (test-equal obj)
(apply (car (test-form obj))
(cdr (test-form obj)))
(test-value obj))
t
nil))

Part 2: Creating a Hash Table Mixin

(defclass hash-mixin ()
((key :initarg :key :accessor key)
(table :accessor table
:allocation :class
:initform (make-hash-table :test #'equal))))
  • Now, looking a bit farther ahead (and beyond this article), we would likely want to have different hash tables for different types of CLOS objects. If we have a TEST-CLASS and a BOOK-CLASS, we likely do not want instances of both classes to share the same hash table.
  • Hence, we will subclass HASH-MIXIN to isolate a hash-table specifically for test objects. The slot definition for TABLE in TEST-HASH-MIXIN shadows the same slot in its parent class HASH-MIXIN.
(defclass test-hash-mixin (hash-mixin)
((table :accessor table :allocation :class
:initform (make-hash-table :test #'equal))))

Part 3: Creating an Aggregate Class

(defclass unit-test (test-hash-mixin fundamental-test) ())

Part 4: Adding in Functionality

4.1 Adding Tests to the Hash Table [C]

(defmethod initialize-instance :after ((obj hash-mixin) &key)
(setf (gethash (key obj) (table obj)) obj))

4.2 Reading Tests from the Hash Table [R]

(defun read-test (obj)
(gethash (key obj) (table obj)))

4.3 Updating Tests in the Hash Table [U]

(defmethod (setf key) :before (key (obj hash-mixin))
(setf (gethash (key obj) (table obj)) nil))
(defmethod (setf key) :after (key (obj hash-mixin))
(setf (gethash (key obj) (table obj)) obj))

4.4 Deleting Tests in the Hash Table [D]

(defun delete-test (obj)
(setf (gethash (key obj) (table obj)) nil))

Part 5. Bringing it all together

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ashok Khanna

Ashok Khanna

Masters in Quantitative Finance. Writing Computer Science articles and notes on topics that interest me, with a tendency towards writing about Lisp & Swift