Loading every example into one REPL
File: load.lisp
Fifteen of the sixteen example programs end with demo calls (osascript.lisp keeps its examples in comments, and load.lisp is the seventeenth file). Demos help when you run a script but get in the way when you want every definition in one REPL. load.lisp reads each file form by form and evals only the definition forms.
The code
1 ;; (load "load.lisp") then (help): loads definitions from every file,
2 ;; skipping the example calls at the bottom of each file.
3 #-quicklisp (load "~/quicklisp/setup.lisp")
4
5 (let ((dir (directory-namestring
6 (or *load-truename* *default-pathname-defaults*))))
7 (dolist (f (directory (merge-pathnames "*.lisp" dir)))
8 (unless (equal (pathname-name f) "load")
9 (with-open-file (s f)
10 (let ((*package* (find-package :cl-user)))
11 (loop for form = (read s nil s) until (eq form s)
12 when (and (consp form)
13 (member (car form)
14 '(defun defmacro defstruct defclass
15 defgeneric defmethod defvar
16 defparameter defconstant defpackage
17 in-package require load
18 ql:quickload)))
19 do (eval form)))))))
20
21 (defparameter *help*
22 '(("apple-system-model.lisp")
23 ("(apple-fm \"what is 1 + 10?\")"
24 "on-device Apple model via `fm`")
25 ("gemini.lisp")
26 ("(gemini \"hi\" [model])"
27 "Google Gemini (GOOGLE_API_KEY)")
28 ("ollama.lisp")
29 ("(ollama \"hi\" [model])"
30 "local Ollama model")
31 ("sparql.lisp")
32 ("(sparql endpoint \"SELECT ...\")"
33 "SPARQL query -> rows of (var . value)")
34 ("(dbpedia \"SELECT ...\")"
35 "query DBpedia")
36 ("(wikidata \"SELECT ...\")"
37 "query Wikidata")
38 ("lightpanda.lisp")
39 ("(lightpanda url [\"markdown\"])"
40 "JS-rendered page via Lightpanda")
41 ("(links html)"
42 "href strings in an HTML string")
43 ("webscraping.lisp")
44 ("(fetch url)"
45 "fetch and parse a page (plump DOM)")
46 ("(text node)"
47 "plain text of a plump node")
48 ("(clean string)"
49 "trim spaces, collapse blank lines")
50 ("(headers url)"
51 "h1-h6 texts of a page")
52 ("(page-text url)"
53 "readable plain text of a page")
54 ("(dom url-or-dom)"
55 "fetch a URL, or pass a parsed DOM through")
56 ("search.lisp")
57 ("(esearch \"query\" [n])"
58 "Exa search -> (title url text)")
59 ("(bsearch \"query\" [n])"
60 "Brave search -> (title url text)")
61 ("(curl-json &rest curl-args)"
62 "run curl, parse JSON reply")
63 ("(results items text-key)"
64 "hits -> (title url text) lists")
65 ("(api-key \"ENV_VAR\")"
66 "read an env var or signal an error")
67 ("(unescape string)"
68 "decode common HTML entities")
69 ("osascript.lisp")
70 ("(osascript \"return 1 + 10\")"
71 "run AppleScript, return stdout")
72 ("(mail-unread-count)"
73 "Mail inbox unread count")
74 ("(get-todays-events)"
75 "today's Calendar event titles")
76 ("(add-reminder \"Buy milk\")"
77 "add a Reminders item")
78 ("(send-imessage \"+1555...\" \"Hi\")"
79 "send an iMessage")
80 ("(read-recent-imessages 3)"
81 "recent iMessages as JSON")
82 ("(safari-login url user password)"
83 "fill and submit a Safari login form")
84 ("symbolic-math.lisp (p = (poly 3 -1 5) is 3x^2 - x + 5)")
85 ("(poly 3 -1 5)"
86 "polynomial from coefficients")
87 ("(normalize terms)"
88 "combine like terms, sort")
89 ("(p+ p q ...) (p- p q) (p* p q)"
90 "add / subtract / multiply polynomials")
91 ("(scale p 2)"
92 "multiply by a constant")
93 ("(degree p) (evaluate p 2)"
94 "degree / value at x")
95 ("(deriv p [n])"
96 "nth derivative")
97 ("(integ p [n])"
98 "nth antiderivative (no +C)")
99 ("(bound :pi)"
100 "bound -> float (numbers, :pi, :e)")
101 ("(definite p 0 1)"
102 "definite integral from a to b (exact for rationals)")
103 ("(critical-point-p p 1/6)"
104 "is p'(x) = 0 ?")
105 ("(->string p)"
106 "p as text: 3x^2 - x + 5")
107 ("(integral->string p 0 1)"
108 "integral as text")
109 ("bayes.lisp")
110 ("(bayes-update dist evidence l-fn)"
111 "Bayes update -> normalized posterior alist")
112 ("(bayes-normalize dist)"
113 "normalize alist probabilities to sum to 1.0")
114 ("(map-hypothesis dist)"
115 "maximum a posteriori (MAP) hypothesis pair")
116 ("triple-store.lisp")
117 ("(add-triple s p o)"
118 "add (s p o) triple to store")
119 ("(query-triples patterns [store])"
120 "query graph via pattern match & relational join")
121 ("(match-triple pattern triple env)"
122 "unify one pattern with one triple -> env or :fail")
123 ("(var-p x)"
124 "is x a ?variable symbol")
125 ("autograd.lisp")
126 ("(val number)"
127 "wrap scalar in autograd computation node")
128 ("(v+ a b) (v* a b) (v-relu a)"
129 "autograd scalar math operations")
130 ("(backward root)"
131 "reverse-mode automatic differentiation backprop")
132 ("bm25.lisp")
133 ("(tokenize text)"
134 "extract alphanumeric lowercase tokens")
135 ("(bm25-search corpus query)"
136 "Okapi BM25 ranked document retrieval")
137 ("hopfield.lisp")
138 ("(hopfield-train patterns size)"
139 "Hebbian training -> 2D weight matrix")
140 ("(hopfield-recall w input [max-sweeps])"
141 "recall until stable -> state, sweeps used")
142 ("(hopfield-energy w state)"
143 "Lyapunov energy function")
144 ("(show-pattern pat [width])"
145 "render bipolar pattern as #/. grid")
146 ("vector-store.lisp")
147 ("(make-vector-store)"
148 "create in-memory dense vector store")
149 ("(store-add store id text vec)"
150 "add labeled vector to store")
151 ("(store-search store qvec [k])"
152 "top-K nearest neighbors by cosine similarity")
153 ("(v-dot a b)"
154 "dot product of two vectors")
155 ("(v-norm a)"
156 "Euclidean norm of a vector")
157 ("(v-cosine a b)"
158 "cosine similarity between vectors")
159 ("summarizer.lisp")
160 ("(summarize text [n])"
161 "extractive text summarization (top-N sentences)")
162 ("(words text) (split-sentences text)"
163 "NLP tokenization and sentence segmentation")
164 ("load.lisp")
165 ("(help [filter])"
166 "print this list (optionally filtered by string)")))
167
168 (defun help (&optional filter)
169 (let ((filter (and filter (string filter))))
170 (dolist (h *help*)
171 (if (cdr h)
172 (when (or (null filter)
173 (search filter (first h) :test #'char-equal)
174 (and (second h)
175 (search filter (second h) :test #'char-equal)))
176 (format t " ~34a ; ~a~%" (first h) (second h)))
177 (when (null filter)
178 (format t "~a~%" (first h))))))
179 (values))
How it works
- The loader finds its own directory with
*load-truename*, visits every.lispfile except itself, and reads forms with(read s nil s), a classic idiom that uses the stream itself as the end-of-file marker. - It evaluates only forms whose
caris on the whitelist (defun,defmacro,defstruct,defclass,defmethod,defvar,defparameter, …). The book’s files use a few of these, but the full set keeps the loader working when you add your own files to the directory. It skips top-level demo calls, which is why each file can end in demos and still load as a library. - Binding
*package*tocl-userduring reads makes symbols read the same way no matter which package the REPL is in. *help*is a data-driven catalog: one-element lists are section headers (file names), and two-element lists hold a call signature and a description.helpprints everything, or only rows that match a filter string (case-insensitive, against both signature and description), and returns(values)(no value) to keep REPL output tidy.
Running it
1 * (load "load.lisp")
2 * (help "search")
3 (esearch "query" [n]) ; Exa search -> (title url text)
4 (bsearch "query" [n]) ; Brave search -> (title url text)
5 (bm25-search corpus query) ; Okapi BM25 ranked document retrieval
6 (store-search store qvec [k]) ; top-K nearest neighbors by cosine similarity
The filter is a plain substring match, so (help "search") finds both the web-search APIs and the two local retrieval engines. (help) with no argument prints the whole catalog grouped by file.
Using it
Load everything once, then mix the chapters in a single session. For example, rank documents with BM25 and summarize the hits, using two chapters with no extra code (real transcript):
1 * (defparameter *corpus*
2 '("Common Lisp is a general-purpose programming language with powerful macros."
3 "Python is an interpreted language known for data science and machine learning."
4 "Deep learning models require automatic differentiation and gradient optimization."))
5 *CORPUS*
6 * (summarize (format nil "~{~a ~}" (mapcar #'second (bm25-search *corpus* "learning"))) 1)
7 ("Deep learning models require automatic differentiation and gradient optimization.")
Other one-liners to try: (summarize (page-text url) 3), or (backward e) after you build a graph with v+ and v*. The selective-eval trick works for your own script collections too: it turns a directory of runnable programs into a library without editing the files.