Common Lisp: A Practical Introduction
Table of Contents
Background
Common Lisp is a dialect of Lisp standardized by ANSI in 1994. It combines functional, procedural, and object-oriented paradigms with a powerful macro system that enables compile-time code generation.
Key Implementations
| Implementation | Description |
|---|---|
| SBCL | Steel Bank Common Lisp (fast) |
| CCL | Clozure Common Lisp |
| ECL | Embeddable Common Lisp |
| ABCL | Armed Bear (JVM-based) |
Getting Started
;; Install SBCL and Quicklisp ;; (load "~/quicklisp/setup.lisp") ;; Basic function definition (defun factorial (n) "Calculate factorial of N." (if (<= n 1) 1 (* n (factorial (1- n))))) (factorial 5) ; => 120 ;; Higher-order functions (mapcar #'1+ '(1 2 3 4 5)) ; => (2 3 4 5 6) (reduce #'+ '(1 2 3 4 5)) ; => 15
Macros
Macros are compile-time code transformations:
;; Define a simple macro (defmacro when-let ((var expr) &body body) "Bind VAR to EXPR and execute BODY if non-nil." `(let ((,var ,expr)) (when ,var ,@body))) ;; Usage (when-let (user (find-user "alice")) (format t "Found: ~a~%" user))
CLOS (Common Lisp Object System)
;; Define a class (defclass person () ((name :initarg :name :accessor person-name) (email :initarg :email :accessor person-email))) ;; Define a method (defmethod greet ((p person)) (format nil "Hello, ~a!" (person-name p))) ;; Create an instance (let ((alice (make-instance 'person :name "Alice" :email "alice@example.com"))) (greet alice)) ; => "Hello, Alice!"