I'm now starting on Practical Common Lisp, having gone through Gentle Introduction to Symbolic Computation, and I'm playing around with the sample CD database that PCL describes on pp. 20-36. PCL uses a p-list to store each record of a CD collection. I decided to vary the storage implementation a little bit by using a p-list, a hash, and a struct to store the CD record
I then create an a-list of functions corresponding to the particular type of implementation:
This approach should be familiar to C-programmers who implement polymorphism by indexing into an array of function pointers. I've merely applied the technique to Lisp. My question is: Is this a standard practice in Lisp? When I read about polymorphism in Lisp, I usually encounter generic functions (which are covered in a later chapter of PCL), but I wonder if this approach is as commonly accepted.
(defstruct database
(type 'plist) ; Could also be a 'hash or a 'struct
(storage nil)) ; A list which stores the collection of records
(defun db-create (db-type)
(make-database :type db-type :storage nil))
The function DB-CREATE takes a symbol specifying the particular type of implementation: PLIST, HASH, or STRUCT.I then create an a-list of functions corresponding to the particular type of implementation:
(defconstant *dispatch-table*
'((plist (:construct plist-construct :get plist-get))
(struct (:construct struct-construct :get struct-get))
(hash (:construct hash-construct :get hash-get))))
(defun dispatch (database operation)
(let ((dbtype (database-type database)))
(getf (second (assoc dbtype *dispatch-table*))
operation)))
(defun dbrecord-construct (db title artist rating ripped)
(let ((func (dispatch db :construct)))
(funcall func title artist rating ripped)))
(defun dbrecord-get (db record field)
(let ((func (dispatch db :get)))
(funcall func record field)))
The DBRECORD-CONSTRUCT function resolves to PLIST-CONSTRUCT, STRUCT-CONSTRUCT, or HASH-CONSTRUCT to build a record out of CD data, while DBRECORD-GET retrieves a particular field out of a database record.This approach should be familiar to C-programmers who implement polymorphism by indexing into an array of function pointers. I've merely applied the technique to Lisp. My question is: Is this a standard practice in Lisp? When I read about polymorphism in Lisp, I usually encounter generic functions (which are covered in a later chapter of PCL), but I wonder if this approach is as commonly accepted.