Colin Lupton — Random Lisp Libraries: cl-interleave

· 8 hours ago

Today's random Lisp library pitched by Claude is cl-interleave, providing controlled scheduling and systematic interleaving tests for threaded Common Lisp.

I spent some time yesterday improving my custom common-lisp Skill to be more aware of the complete ecosystem, so you'll notice that this library makes references across a much larger space. It does more validation of novelty and need against available Lisp libraries, with a breadth-first strategy. And in this particular case, it's pulling toolchains from Rust, the JVM, and .NET for inspiration. The library was also designed to be complementary to yesterday's library, cl-failpoints, with direct integration planned for v0.2.

Claude sure struggled with the implementation of this library, though. It took three tries to successfully implement DPOR, churning away all morning to get it working right. Apparently its first two attempts were based on the original paper, the third on later work.

You can find the generated codebase at github.com/thephoeron/cl-interleave

Quicklisp news — November 2026 Quicklisp dist update now available

· 11 hours ago

 New projects:

  • 0conf — Pure Common Lisp mDNS (RFC 6762) and DNS-SD (RFC 6763) implementation. — MIT
  • adjuvant — Various utility functions and macros used in several packages. — MIT
  • affinity — A higher layer of abstraction over CFFI. — MIT
  • akshara — OpenType shaping: GSUB and GPOS through zpb-ttf, an Indic shaper for Devanagari, Bengali, Tamil, Telugu and Gujarati. — MIT
  • anansi — Rate-limited function calls with special support for mitigating potential denial of service on web login forms. — Unlicense / Public Domain
  • ariadne — A graph database in Common Lisp with SPARQL-like query DSL — MIT
  • asdf-macos-app — ASDF extension that builds macOS .app bundles from SBCL images. — MIT
  • autoload — An ASDF autoloading facility. See AUTOLOAD::@AUTOLOAD-MANUAL. — MIT, see COPYING.
  • batten — NURBS curves and surfaces in portable Common Lisp: a port of NLib from NVIDIA's open-source SMLib. — Apache-2.0
  • bgapi — Silicon Labs BGAPI for Common Lisp. — Zlib
  • binstruct — Declarative binary structure encoding and decoding for Common Lisp. — Apache-2.0
  • brake — An extended breakpoint facility for Common Lisp — MIT
  • buffered-streams — Buffered streams for efficient seeking and backtracking. — Apache-2.0
  • celosia — Tool for handling SMS Graphics Compression/Decompression — LicenseRef-Hippocratic-3.0 WITH AdditionRef-AI-Use-Restriction-Addendum-1.0
  • charje.asdf-cli — Wrap some ASDF (and quickproject) functions for ASDF project management from the command line. — AGPL V3 or any later version
  • charje.loop — Charles Ergonomic, Extensible, Efficient Loop Abstraction — AGPL V3 or any later version
  • charmed — Charmed - Pure-Lisp ANSI terminal control library — MIT
  • chroma — System for colour representation, conversion, and operation. — zlib
  • cl-battlesnake — A Common Lisp framework for building Battlesnake AIs — 0BSD
  • cl-brotli — Common Lisp bindings for the brotli compression library, with Gray streams API. — LGPL-3.0-or-later
  • cl-cancel — Cancellation propagation library for Common Lisp with deadlines and timeouts — MIT
  • cl-cdp — Chrome DevTools Protocol (CDP) client for Common Lisp, auto-generated from the official protocol spec. — MIT
  • cl-colors-ng — Simple color library for Common Lisp — Boost Software License - Version 1.0
  • cl-dasl — DASL encoder/decoder — MIT
  • cl-docx — Simple Reader and Writer library for Docx files in Common Lisp — MIT
  • cl-feiertage — Common Lisp library for calculating German and Austrian bank holidays — MIT
  • cl-flac-metadata-bindings — Bindings for the metadata related sections of libFLAC — BSD-2-Clause
  • cl-freedesktop-notifications — A wrapper of the Freedesktop notifications specification. — MIT
  • cl-ganzhi — Convert Gregorian calendar date time to Chinese GanZhi calendar (also known as Sexagenary Cycle Calendar) date time. — 3-Clause BSD
  • cl-gtk4 — GTK4 bindings for Common Lisp. — LGPLv3
  • cl-iparse — A Common Lisp port of Clojure's instaparse parser library. Implements the GLL (Generalized LL) parsing algorithm with support for ambiguous and left-recursive grammars, EBNF notation, and efficient parsing. — EPL-1.0
  • cl-libheif — A wrapper around libheif — 2-clause BSD
  • cl-llm-provider — Unified Common Lisp interface for multiple LLM provider APIs (Anthropic, OpenAI, Gemini, Ollama, OpenRouter) — MIT
  • cl-mcp — Model Context Protocol server for Common Lisp — MIT
  • cl-mpris — A wrapper library over the MPRIS DBus inteface specification for media players. — MIT
  • cl-nbt — this library provides simple ways to create Minecraft Bedrock NBT files — MIT
  • cl-opendaq — Common Lisp bindings for openDAQ. — MIT
  • cl-pam — Pure Lisp PAM implementation. — 0BSD
  • cl-pdfrune — Ultra-Fast, Memory-Safe, Permissive PDF Engine in Common Lisp — MIT or Apache-2.0
  • cl-postgres-client — A high-level PostgreSQL client on top of cl-postgres, in the style of Spring's JdbcClient — MIT
  • cl-robdd — a CL implementation of Reduced Ordered Binary Decision Diagrams, ROBDD — MIT
  • cl-rte — Regular type expressions implementation — MIT
  • cl-selfupdate — Self-update functionality for Common Lisp executables via GitHub/GitLab Releases — MIT
  • cl-simple-matrix — Functions to work with matrices. — GPL-3
  • cl-taglib-bindings — Read and write metadata of audio files using Common Lisp (Taglib bindings) — Apache 2.0
  • cl-theora — A decoder library for the OGG/Theora video format via the theorafile C library — zlib
  • cl-uf2 — Microsoft UF2 & BIN format convert tools. — GPL-3.0
  • cl-universal-tween-engine — Common Lisp port of Universal Tween Engine — Apache-2.0
  • cl-unum — A Common Lisp implementation of [John L. Gustafson](https://en.wikipedia.org/wiki/John_Gustafson_(scientist))'s [unum](https://en.wikipedia.org/wiki/Unum_(number_format))s as described in [The End of Error](https://www.crcpress.com/The-End-of-Error-Unum-Computing/Gustafson/p/book/9781482239867) — MIT
  • cl-z3 — Common Lisp bindings for the Z3 SMT solver. — MIT
  • clatter-irc — Modern Common Lisp IRC library with IRCv3 support — MIT
  • cliff — CLI library for Common Lisp. Handles args, env vars, and conf — MIT
  • cliif-common-lisp — CLIIF is to Common Lisp what JSON is to JS. Includes a carrier transport for JSON, and is capable of streaming ND-CLIIF. — MIT
  • cm — Common Music — LLGPL
  • cmn — Common Music Notation — MIT
  • conserve — Yet Another CSV Library for Common Lisp. — MIT/X11
  • cose-sign1 — COSE Sign1 for Common Lisp — MIT
  • datastar-cl — Common Lisp implementation of the Datastar SDK for Server-Sent Events (SSE) — MIT
  • deploy-command-line — A simple command line option interface for applications used with Deploy. — zlib
  • dref — Reify definitions, provide portable access to arglists, docstrings and source locations in an extensible framework. — MIT, see COPYING.
  • dsl-quote — A lightweight DSL quotation and expansion engine for Common Lisp. — MIT
  • fast-csv — Fast, RFC 4180 compliant CSV parser — MIT
  • faster — A Common Lisp library for processing FASTQ files faster. — MIT
  • frame-chronicle — A simple thread-safe way to collect game state on specific frames — Unlicense / Public Domain
  • frostlake — A dependency-free Common Lisp driver for the Frostlake database engine. — Apache-2.0
  • ftw — Common Lisp For the Win(32). A very thin layer over the top of Win32 GUI APIs. — MIT
  • functional-json — A package for working with JSON, based on ST-JSON. — BSD
  • ingot — Git in Common Lisp: objects, packs, refs, trees, commits, diffs, patches, blame, merges, the smart protocol's server side, archives. No subprocess, no git binary. — MIT
  • keynub-licdongle — KeyNub License Dongle: verify that a dongle is genuine, read and write the license records it holds, use its hardware counters and seal data that only a dongle can open. — Apache-2.0
  • lc-sse — lc-sse: generic SSE library (umbrella: core + Hunchentoot + Clack) — LGPL-3.0-or-later
  • line-readtable — Describe line-readtable here — BSD-2 Clause
  • lisp-types — Lisp type reduction utilities, and CL type-system compatible ROBDD implementation — MIT
  • lp-hash-table — Pretty fast insertion-ordered linear-probing hash tables and sets — Public Domain
  • ls-server — HTTP server for the Lisp-Stat system — MS-PL
  • mandelascii — Realtime 64bit ascii mandelbrot zoomer in Common Lisp — BSD-3-Clause
  • mu-json — A tiny JSON parser — LLGPL
  • native-handles — Retrieve the native handle of an operating system-backed resource of your implementation, such as streams, sockets, threads, etc. — zlib
  • native-repl — A portable, native, drop-in REPL for interactive command lines. — zlib
  • ndfa — Implementation of non-deterministed finite automata — MIT
  • ningle-actions — Server actions for Ningle — MIT
  • ningle-fbr — File-based router for Ningle — MIT
  • nrdl — Nestable Readable Document Language — MIT
  • observables — A library for defining activity/changes on objects that can be observed by remote trigger functions — zlib
  • openweathermap — Common Lisp client for OpenWeatherMap APIs — MIT
  • opsis — Condition-based observability for Common Lisp — MIT
  • package-doc-dump — Simple API doc generator - dumps docstrings, names, lambda lists of all external symbols in specified packages to an HTML file. In the order the symbols are specified in the defpackage forms. — MIT
  • parcom — A simple parser combinator library. — MPL-2.0
  • parsonic — Fast parser combinators and compiler for Common Lisp. — Apache-2.0
  • pddl-tools — Common lisp library for manipulating PDDL expressions. — BSD 3-clause
  • peaky-binders — Functions that generate the code to bind lambda lists — MIT
  • posix-pipes — Describe posix-pipes here — LGPL
  • pure-tls — Pure Common Lisp TLS 1.3 implementation — MIT
  • quick-plot — A Grammar of Graphics plotting library for Common Lisp providing quick statistical visualizations and layered customization. — MS-PL
  • quicklisp-https — Https support patch for quicklisp. — MIT
  • reckless-utf8 — GC-friendly UTF8 encoder/decoder — BSD-2-Clause
  • rewrite-cl — Read, modify, and write Common Lisp source code while preserving whitespace and comments — MIT
  • roboter — An implementation of the RFC 9309 Robots Exclusion Protocol for parsing robots.txt files — MIT
  • screamer — Nondeterministic programming and constraint propagation. — MIT
  • scrutiny — Unit Test Facility, similar but simpler then lisp-unit. Slime-compatible — MIT
  • skiptrace — Audits Common Lisp reader conditionals across implementation feature profiles. — MIT
  • sta6 — Tiny static site generator that turns `pages/*.lisp` into `build/*.html` — GPLv2
  • stat-generics — Generic function definitions for statistical operations — MS-PL
  • sunny-side — A minimal, pure-Lisp Gherkin engine: parses .feature files and runs each Scenario as an ordinary FiveAM test. No Ruby, no wire protocol, no subprocess. — BSD-3-Clause
  • system-auth — A library to authenticate against system user accounts (PAM etc.) — zlib
  • tailwind-merge — Utility library to merge Tailwind CSS classes without style conflicts. — Unlicense
  • telos — Intent introspection for Common Lisp — make the WHY queryable — MIT
  • threadmilambda — ThreadMILambda makes writing portable multi-threaded code simple(r). Notes: This library is a fork of Bordeaux Threads, moved to... Milan (or Miλan). — MIT
  • tomlet — TOML parser for Common Lisp — MIT
  • trivial-compile-file — Standardises the behaviour of compile-file around source locations and compiler messages. — zlib
  • trivial-deprecate — A library implementing a simple deprecation mechanism — zlib
  • trivial-glob — Shell-style glob pattern matching and filesystem globbing for Common Lisp — MIT
  • trivial-svg — Pure Lisp SVG renderer. — 0BSD
  • uclp — An experimental implementation of Parsing Expression Grammers in Common Lisp — MIT
  • vault — A vault of functions — MIT
  • wscli — RFC 6455 WebSocket client TLS (cl+ssl). — BSD-2-Clause
  • yamson — Fast YAML and JSON parsers for Common Lisp. — Apache-2.0

Updated projects: 3bmd, 3bz, 3d-math, 40ants-asdf-system, 40ants-slynk, abstract-arrays, adhoc, adopt, adp-github, alexandria-plus, alexandria, also-alsa, alternate-asdf-system-connections, anypool, april, asdf-finalizers, aserve, atomics, beast, bike, binary-structures, bknr-datastore, bobbin, bp, bytecurry.mocks, cephes.cl, cffi-object, cffi, chain, champ-lite, chancery, chipi, chipz, ci, cl+ssl, cl-all, cl-atelier, cl-avro, cl-batis, cl-binary-store, cl-bmp, cl-brewer, cl-bus, cl-catmull-rom-spline, cl-ceigen-lite, cl-cf, cl-chise, cl-collider, cl-concord, cl-confidence, cl-cont, cl-containers, cl-cookie, cl-cpus, cl-cron, cl-csv, cl-data-structures, cl-db3, cl-dbi-connection-pool, cl-dbi, cl-dct, cl-digraph, cl-double-metaphone, cl-duckdb, cl-editdistance, cl-environments, cl-fad, cl-flx, cl-forms, cl-freelock, cl-frugal-uuid, cl-gamepad, cl-getx, cl-github-v3, cl-gobject-introspection, cl-gog-galaxy, cl-gserver, cl-hamcrest, cl-i18n, cl-info, cl-jingle, cl-jpeg, cl-jschema, cl-ktx, cl-kyoto-cabinet, cl-ledger, cl-libre-translate, cl-markless, cl-marshal, cl-memcached, cl-migratum, cl-minifloats, cl-mixed, cl-modio, cl-mpg123, cl-naive-deprecation, cl-naive-tests, cl-netpbm, cl-ntp-client, cl-ntriples, cl-online-learning, cl-opengl, cl-patterns, cl-pcg, cl-peppol, cl-plus-ssl-osx-fix, cl-prevalence, cl-protobufs, cl-random-forest, cl-sanitize-html, cl-sendgrid, cl-steamworks, cl-str, cl-telegram-bot-media, cl-transducers, cl-tuition, cl-turbojpeg, cl-utils, cl-voipms, cl-vorbis, cl-wavefront, cl-wavelets, cl-webkit, cl-xmpp, cl-yahoo-finance, cl-zstd, clack-cors, clack-prometheus, clack, clad, classimp, classowary, clavier, cleopter, climacs, clingon, clith, clj-con, clml, clog, closer-mop, clq, clx, cmd, coalton, cocoas, collidxr, com-on, command-line-arguments, common-lisp-jupyter, commondoc-markdown, consfigurator, croatoan, csv, ctype, data-frame, defclass-std, defmain, defrest, deploy, dexador, dfio, dissect, distributions, djula, doc-plantuml, doc, docs-builder, dsm, dual-numbers, easy-audio, easy-routes, ecclesia, eclector, expanders, f2cl, fare-csv, fare-memoization, fare-quasiquote, fare-scripts, fare-utils, fast-http, femlisp, file-notify, file-select, fiveam-matchers, float-features, fold, font-discovery, fresnel, fset, function, functional-trees, fuzzy-dates, fxml, gendl, generic-arithmetic, generic-comparability, genhash, glfw, global-vars, glsl-toolkit, gtirb-capstone, gtirb-functions, harmony, hiccl, house, hsx, http2, hu.dwim.quasi-quote, hunchentoot-recycling-taskmaster, idna, imagine, imago, incless, infix-math, inravina, invistra, journal, jpeg-turbo, json-mop, jsonrpc, jsown, khazern, knx-conn, lack, lemmy-api, lftp-wrapper, lichat-protocol, lichat-tcp-client, linear-programming-glpk, linear-programming, lisa, lisp-binary, lisp-stat, lispbuilder, literate-lisp, live-cells-cl, lla, lmdb, local-time, log4cl-extras, logging, lru-cache, luckless, lunamech-matrix-api, machine-state, maiden, mailgun, markup, math, mcclim, metabang-bind, mgl-gpr, mgl-mat, mgl-pax, mgl, micmac, misc-extensions, mito-auth, mito, mk-defsystem, mmap, mnas-package, mnas-path, modularize-hooks, modularize-interfaces, modularize, multiposter, mutility, mutils, named-let, named-readtables, netaddr, nfiles, nibbles, nodgui, nontrivial-gray-streams, numerical-utilities, nyaml, nytpu.lisp-utils, omglib, open-location-code, open-with, openrpc, osc, overlord, package-renaming, parachute, pathname-utils, peltadot, perceptual-hashes, pgloader, pithy-xml, plantuml, plot, plump-sexp, plump, pooler, pp-toml, prettier-builtins, prometheus-gc, prometheus.cl, ptc, py4cl2-cffi, qlot, quaviver, queen.lisp, random-sampling, random-state, reblocks-auth, reblocks-file-server, reblocks-lass, reblocks-navigation-widget, reblocks-parenscript, reblocks-prometheus, reblocks-typeahead, reblocks-ui, reblocks-ui2, reblocks-websocket, reblocks, roan, routes, rove, rs-json, sanity-clause, sapaclisp, sc-extensions, scrapycl, sel, select, serapeum, shop3, simple-inferiors, sip-hash, sketch, slite, sly, smoothers, snappy, special-functions, speechless, spinneret, st-json, staple, star, static-dispatch, statistics, studio-client, stumpwm, swank-client, swank-crew, sycamore, teddy, termp, testiere, text-draw, tfeb-lisp-hax, tooter, trinsic, trivial-arguments, trivial-features, trivial-garbage, trivial-gray-streams, trivial-indent, trivial-inspect, trivial-macroexpand-all, trivial-main-thread, trivial-octet-streams, trivial-package-local-nicknames, trivial-package-locks, trivial-thumbnail, trivial-time, trivial-toplevel-prompt, trivial-utf-8, type-templates, typo, ubiquitous, uncursed, usocket, vellum, verbose, wayflan, websocket-driver, woo, wordnet, wouldwork, wuwei, xhtmlambda, xmls, yah, yason, zacl, zippy, zpb-ttf.

Removed projects: avl-tree, binary-parser, binary-search-tree, cl-flat-tree, cl-irregsexp, cl-jsonpath, cl-kaputt, cl-marklogic, cl-mathstats, cl-opsresearch, cl-sam, cl-spidev, cl-tokyo-cabinet, clnuplot, clod, colored, commonqt, cricket, cubic-bezier, deoxybyte-gzip, deoxybyte-io, deoxybyte-systems, deoxybyte-unix, deoxybyte-utilities, doubly-linked-list, dungen, dynamic-array, fast-generic-functions, freebsd-sysctl, green-threads, grid-formation, gute, hdf5-cffi, helambdap, identifier-pool, json-responses, lisp-chat, mfiano-utils, mockingbird, more-cffi, openai-openapi-client, openapi-generator, origin, patchwork, pettomato-deque, pettomato-indexed-priority-queue, qt-libs, quad-tree, quicksearch, random-uuid, red-black-tree, regular-type-expression, rock, seedable-rng, shadow, slot-map, sparse-set, teepeedee2, tile-grid, trivial-tco, umbra, zsort.

To get this update, use (ql:update-dist "quicklisp")

Enjoy!

Colin Lupton — Random Lisp Libraries: cl-failpoints

· 34 hours ago

Today's scheduled pitch from Claude was for cl-failpoints, providing named fault-injection points and systematic failure sweeps for Common Lisp. Released under the MIT License.

Claude pulled another popular Rust project, the fail crate, out of its hat as the basis for this pitch. I'll have to reword the scheduled task to widen the scope of its pitch selection a bit more. But this is a pretty cool and useful tool. Claude even added a "Who benefits" section to its pitch, which I love, so I'll be asking for that explicitly moving forward.

I've improved the workflow a bit more. Once I approve source-code generation at each step of the plan, it includes the generated code as attached files in the workspace which I can preview in Claude right next to the chat like other attached documents. What I'd like is one more step in the iterative refinement, to generate code block by block, assembling them in files at the end of each project-level step, so that I can comment on and refine every top-level form as it is conceived. I'll keep working toward that.

You may also notice I've worked out some kinks with attribution. Making sure Claude's work is all attributed to Claude, only taking credit for what I do explicitly by listing myself as Maintainer and Orchestrator, and correctly attributing Claude in Git commits as a "co-author" to avoid the legal uncertainty of copyright law when it comes to AI agent models. Commits also link to both me and Claude, which is more like it.

You can find the source-code on GitHub at: github.com/thephoeron/cl-failpoints/

Joe Marshall — Updates to named-let

· 2 days ago

Updating named-let: ignored bindings, multi-form inits, and more

named-let is a small Common Lisp library of Scheme-inspired binding macros: named-let, named-lambda, letrec, letrec*, flambda, and a Lisp-1 style define. It also provides an extended let that you can shadow-import in place of the standard one. This post describes a round of changes to the library: a new way to ignore bindings, clarified handling of multi-form bindings, a bug fix, and improvements to documentation and tests.

Ignored bindings with _

Sometimes you want to bind something only for its side effect. In standard Common Lisp you must invent a variable and declare it ignored:

(let ((a 22)
      (dummy1 (format t "foo"))
      (b (sqrt 2))
      (dummy2 (format t "bar")))
  (declare (ignore dummy1 dummy2))
  body)

Now the extended let does this for you. Any binding of the symbol _ is replaced by a fresh uninterned symbol (a gensym), and a single ignore declaration for all such symbols is added at the start of the body:

(let ((a 22)
      (_ (format t "foo"))
      (b (sqrt 2))
      (_ (format t "bar")))
  body)

;; expands to

(let ((a 22)
      (#:ignore-1 (format t "foo"))
      (b (sqrt 2))
      (#:ignore-2 (format t "bar")))
  (declare (ignore #:ignore-1 #:ignore-2))
  body)

A few details worth knowing:

  • The init forms are still evaluated, and in order, so _ is useful for side effects.
  • You can have any number of _ bindings; each gets its own gensym, so there is no “variable occurs more than once” error.
  • The bare forms _ and (_) are accepted and bind to nil.
  • _ is matched by name, not by identity, so it works no matter which package your code is read in.
  • A declare at the start of your own body coexists with the generated one.
  • Because the generated declaration is placed first, the ignored variable can never be referenced from the body; _ is not a variable you can read.

The same convention applies to a named let, because its bindings become the parameters of a named-lambda, and to named-lambda parameters themselves:

(funcall (named-lambda second-arg (_ x _) x) 1 3 2)
;; => 3

(funcall (named-lambda f (a &optional (_ 9)) (+ a 3)) 1)
;; => 4

Multiple forms in a binding

A binding in the extended let may contain more than one init form. The forms are wrapped in a progn and the last value is bound:

(let ((a (format t "binding a") (+ 2 (sqrt x))))
  (+ a b))

;; expands to

(let ((a (progn (format t "binding a") (+ 2 (sqrt x)))))
  (+ a b))

The library already handled this, so no code change was needed, but it is now pinned down with a test and documented. As in standard Lisp, a bare variable y or a one-element binding (z) is bound to nil, and all bindings are made in parallel: init forms do not see the new variables.

How the expansion works

The extended let looks at its first argument. If it is a list (or nil), it is an ordinary binding list; the macro walks the bindings, replaces each _ with a gensym while collecting the gensyms, and emits the underlying let with the bindings, an optional (declare (ignore ...)), and the body. If the first argument is a symbol, it is the name of a named let and the expansion is a funcall of a named-lambda.

As before, the macros are SERIES-aware. Expansions refer to let and funcall in the SERIES package when it is loaded and the symbol is fbound there, and to COMMON-LISP otherwise. That is why an expansion you inspect in an image with SERIES loaded will begin with series::let. Expansion templates use qualified symbols so they resolve to COMMON-LISP symbols regardless of any shadowing in the consumer's package.

A bug fix in named-lambda

Writing more tests for _ turned up two bugs in named-lambda, which also supports _ parameters:

  1. The binding that extracts an optional docstring had a misplaced parenthesis, which made the let* binding spec malformed and caused a compile error in the macro definition.
  2. It recognised _ by comparing with eq against the symbol named-let::_. A _ read in any other package is a different symbol and so was not recognised, leading to a “variable _ occurs more than once in the lambda list” error. It now compares symbol names, exactly as let does.

Docstrings and comments

Every macro in the library now has a docstring. named-lambda and named-let were missing them, and letrec* had copied letrec's text; it now says its bindings are initialised sequentially so later ones can use earlier ones. I also added short comments in the places where the code is not self-explanatory: the gensym-and-declare logic in let, the difference between letrec (simultaneous assignment) and letrec* (sequential assignment), and the _ handling in named-lambda.

Tests

The FiveAM suite grew from 24 to 44 checks. The new tests cover:

  • _ in let: evaluation order of the init forms, the shape of the expansion (distinct uninterned symbols and a single declare), bare _ and (_), all-_ binding lists, and a user declare alongside the generated one.
  • Multi-form bindings, both the expansion and the resulting value and side effects.
  • Parallel binding semantics and a let with only a declare in its body.
  • named-lambda with repeated _ parameters, _ with a default in &optional, and a docstring.

Run them with (asdf:test-system "named-let-test"). One practical note when writing your own: do not use names locked by the implementation (such as loop or count) as the name of a named let.

Documentation

The README was rewritten with a summary table and examples for every macro, including the previously undocumented flambda. Along the way I corrected a few inaccuracies: the clone URL, and the claim that define defines local functions (it is a top-level form that stores the function in the symbol's value cell and defines a macro that funcalls it).

There is also a short section on choosing a name for a named let. When the name just means “go around again”, a short one such as next or l reads well:

(named-let next ((i 0) (acc '()))
  (if (= i 5)
      (nreverse acc)
      (next (1+ i) (cons (* i i) acc))))
;; => (0 1 4 9 16)

You cannot call it loop: COMMON-LISP already binds that symbol as a macro, and implementations such as SBCL lock the package. The same is true of other standard names like count.

Getting it

The code is on GitHub at jrm-code-project/named-let. Clone it into your Quicklisp local-projects directory and load it with (ql:quickload "named-let").

Colin Lupton — Random Lisp Libraries

· 2 days ago

Migrating my AI stack to Claude, I came up with a fun new side-project: pitch me a novel Lisp library every day that fills a gap in the community, as a scheduled task. If I like the pitch, I'll review and refine the plan, generate and test the code, and push it up on GitHub for everyone to enjoy. Once I've had the chance to manually validate the library's correctness and fitness-for-purpose, I may push it to Ultralisp. But for now they're just going straight to GitHub.

The first pitch Claude gave me this morning is for cl-api-ledger. It tracks API changes in Lisp libraries and ensures their versioning conforms to the SemVer 2.0.0 spec, similar to tools such as cargo-semver-checks for Rust and apidiff for Go.

I tried out following the plan and building the library with both Opus 5.5 and Fable 5.2. The Fable run was more polished, so that's the one I pushed. I only got $20 of Usage Credits to try out Fable, though, and this run cost just under $10. So for future runs I'll be sticking to Opus 5.5, at least until I can upgrade to the Max plan.

I have my environment building for the latest SBCL and Quicklisp dist, surveying Quicklisp and Ultralisp for existing libraries, writing tests with Parachute, plus a bunch of other fine-grained stuff of interest. I may write a more general post of Claude tips, so you can get the same interactive-planner based environment as me or simply improve your Lisp environment for Claude Code.

Robert Smith — A faster algorithm for extracting hexadecimal digits of π

· 6 days ago

By Robert Smith

This post introduces a new algorithm for extracting hexadecimal digits of \(\pi\) without computing the preceding digits. It beats the standard term-by-term evaluations of Bailey-Borwein-Plouffe (BBP), Bellard, and Huvent on operation count by a substantial margin.


Contents


The key insights come from the following identity:

\[ \boxed{ \pi = \sum_{k=0}^{\infty} \frac{(-1)^{\lfloor k/2\rfloor}\big(2^{1-3k}+2^{-1-5k}\big) + (-1)^k\big(2^{-1-6k}+2^{-4-10k}\big)}{2k+1}. } \]

The underlying series goes back to Euler, but I’ve rearranged it to exploit more efficient evaluation. Collecting its terms by odd denominators lets us share the arithmetic in two places:

  1. The common denominator \(M=2k+1\) means we can add four remainders and divide once. The surprise is that we don’t have to compute those remainders independently either. The gaps between the exponents are small multiples of \(k\) plus constants, so one starting power and the step \(2^k\bmod M\) let us reach the others by multiplication.

  2. We can also share arithmetic between denominators by using their common factors. We show two ways to do that:

    • Group by denominator pairs: When \(M\) and \(3M\) are both in range, work modulo \(3M\). Two full exponentiations give us up to eight powers of two, and we still divide just once.
    • Group by prime powers: Split each fraction over the prime powers in its denominator. All contributions over the same prime power share one modular exponentiation and one division. The sieve uses asymptotically more memory than pairing, but its running time is also asymptotically improved.

In my AVX-512 implementation, I timed the extraction of 12 hexadecimal digits after skipping the first trillion. On 32 threads, denominator pairing was 1.62× as fast as Huvent and prime-power grouping was 5.56× as fast.

The BBP trick and formula convergence

To see where the savings come from, let’s recall the BBP trick. To skip \(n\) hex digits, shift \(\pi\) left by \(d=4n\) bits and take the fractional part. Shifting by \(d\) bits adds \(d\) to each exponent, so we’re left adding and subtracting terms of the form \(2^E/N\). When \(E\ge 0\), write \(2^E=qN+r\). Then \(2^E/N=q+r/N\), and we don’t care about \(q\): it’s an integer. Even at \(d=4{,}000{,}000\), we can compute \(r=2^E\bmod N\) without ever constructing a four-million-bit numerator.

The terms with \(E<0\) make up the tail. They decay geometrically, so we sum them directly, keeping enough guard bits to settle the last digit we want.

The above is essentially the BBP trick, and is the basis for three decades of digit extraction algorithms.

As such, when I was programmatically looking for efficient BBP-formula, I ranked them by how many fractions I'd have to evaluate to reach a given digit. Each fraction in the main loop costs me a modular exponentiation and a division. Bellard’s formula advances 10 bits for every seven fractions; Huvent’s formula advances 12 bits for every eight. After finding Huvent’s formula independently, I’ve tried feverishly to find one with a better ratio, without success. So I looked toward ways of optimizing existing series.

One clue tipped me off. There’s a choice hiding in the last step of Bellard’s terse derivation. He has one sum in powers of \(1/4\) and another in powers of \(1/1024\). Since \(4^5=1024\), splitting the first sum into five progressions lets him write both sums in powers of \(1/1024\). What if, instead of lining up the powers, we lined up the denominators?

Lining up denominators

Lining up denominators seemed hard with the many-term series of Bellard and Huvent. One good place I found to try this is a series Euler wrote down in 1779, as noted by Craig-Wood, who used it himself to write an extraction program1. The starting point is Hutton’s arctangent identity (which Bellard lists):

\[ 2\arctan\left(\frac13\right)+\arctan\left(\frac17\right)=\frac\pi4. \]

One way to check it is to multiply out \((3-i)^2(7-i)=50(1-i)\) and take the argument of each side. The usual Taylor series for these arctangents would give us powers of 3 and 7. To get powers of two, it helps that \(3=4-1\) and \(7=8-1\).

Consider \(3-i\) for example. Its argument is \(-\arctan(1/3)\). Dividing by four doesn’t change the angle, but it does put the number in a useful form: \((3-i)/4=1-(1+i)/4\). Likewise, \((7-i)/8=1-(1+i)/8\). The imaginary part of a logarithm is the argument, so taking minus the logarithm and keeping its imaginary part gives us the positive angle in each case. Expanding \(-\log(1-z)=\sum_{j=1}^{\infty}z^j/j\), we get

\[ \begin{aligned} F(a) := \arctan\left(\frac{1}{a-1}\right) &= \operatorname{Im}\left[-\log\left(1-\frac{1+i}{a}\right)\right] \\ &= \sum_{j=1}^{\infty}\frac{\operatorname{Im}\big((1+i)^j\big)}{j\,a^j}. \end{aligned} \]

This converges absolutely for both \(a=4\) and \(a=8\), since \(\lvert 1+i\rvert=\sqrt{2}<a\). Hutton’s identity, multiplied by four, now reads \(\pi=8F(4)+4F(8)\).

The first four powers of \(1+i\) are \(1+i,\;2i,\;-2+2i,\;-4\). Their imaginary parts are \(1,2,2,0\): only three terms in each block of four survive. Since the fourth power is \(-4\), increasing \(j\) by four multiplies \((1+i)^j/a^j\) by \(-4/a^4\). That’s \(-1/64\) in \(F(4)\) and \(-1/1024\) in \(F(8)\). Each arctangent gives us three rows, one for each of \(4m+1,\;4m+2,\;4m+3\). For instance, the \(j=1,5,9,\ldots\) row of \(8F(4)\) starts with \(8/4=2\), then \(-2/(5\cdot64)\). In Euler’s formulation the six rows read:

\[ \begin{aligned} \pi ={}& 2\left(1 - \frac{1}{5}\cdot\frac{1}{64} + \frac{1}{9}\cdot\frac{1}{64^2} - \frac{1}{13}\cdot\frac{1}{64^3} + \cdots\right) \\ &+ \frac{1}{2}\left(1 - \frac{1}{3}\cdot\frac{1}{64} + \frac{1}{5}\cdot\frac{1}{64^2} - \frac{1}{7}\cdot\frac{1}{64^3} + \cdots\right) \\ &+ \frac{1}{4}\left(\frac{1}{3} - \frac{1}{7}\cdot\frac{1}{64} + \frac{1}{11}\cdot\frac{1}{64^2} - \frac{1}{15}\cdot\frac{1}{64^3} + \cdots\right) \\[4pt] &+ \frac{1}{2}\left(1 - \frac{1}{5}\cdot\frac{1}{1024} + \frac{1}{9}\cdot\frac{1}{1024^2} - \frac{1}{13}\cdot\frac{1}{1024^3} + \cdots\right) \\ &+ \frac{1}{16}\left(1 - \frac{1}{3}\cdot\frac{1}{1024} + \frac{1}{5}\cdot\frac{1}{1024^2} - \frac{1}{7}\cdot\frac{1}{1024^3} + \cdots\right) \\ &+ \frac{1}{64}\left(\frac{1}{3} - \frac{1}{7}\cdot\frac{1}{1024} + \frac{1}{11}\cdot\frac{1}{1024^2} - \frac{1}{15}\cdot\frac{1}{1024^3} + \cdots\right). \end{aligned} \]

Takahashi writes this more straightforwardly as two sums distinguished by their exponential factors:

\[ \begin{aligned} \pi ={}& \frac{1}{4}\sum_{m=0}^{\infty} \left(-\frac{1}{64}\right)^m \left(\frac{8}{4m+1}+\frac{4}{4m+2}+\frac{1}{4m+3}\right) \\[4pt] &+ \frac{1}{64}\sum_{m=0}^{\infty} \left(-\frac{1}{1024}\right)^m \left(\frac{32}{4m+1}+\frac{8}{4m+2}+\frac{1}{4m+3}\right). \end{aligned} \]

Notice the denominators of the fractions. Since \(4m+2=2(2m+1)\), we can halve the numerator of the middle fraction and leave \(2m+1\) in the denominator. As \(m\) runs over the nonnegative integers, \(2m+1\) gives every positive odd integer. The other two progressions, \(4m+1\) and \(4m+3\), split that same list between them. So each odd denominator appears twice in each sum.

For example, consider the denominator 13. The first progression hits it at \(m=3\); the middle one hits it at \(m=6\), where the original denominator was 26. That’s two contributions from the sum in powers of \(1/64\) and two from the sum in powers of \(1/1024\). The powers are different, but all four numerators can be added before we divide by 13.

Now write the odd denominator as \(2k+1\). The middle fraction reaches it at \(m=k\), so after halving the middle numerators their sum is

\[ \frac12\left(-\frac1{64}\right)^k+\frac1{16}\left(-\frac1{1024}\right)^k =(-1)^k\big(2^{-1-6k}+2^{-4-10k}\big). \]

For the outer two fractions, follow the odd denominators \(1,3,5,7,\ldots\) in order. In the first sum the numerators go \(2,\;1/4,\;-2/64,\;-1/(4\cdot64),\ldots\). Each is one eighth the magnitude of the last, but the sign changes only every two entries, when \(m\) advances. In the second sum the magnitudes start at \(1/2\), then \(1/64\), shrinking by a factor of 32 each time, with the same signs. So at \(2k+1\) their magnitudes are \(2(1/8)^k=2^{1-3k}\) and \(\tfrac12(1/32)^k=2^{-1-5k}\), and their common sign is \((-1)^{\lfloor k/2\rfloor}\). Along with the two middle numerators, that’s all four powers in the boxed formula.

Four powers in two exponentiations

After the shift by \(d\), that is, multiplying the sum by \(2^d\), the four exponents, in the order we wrote them, are

\[ (E_1,E_2,E_3,E_4)=(d+1-3k,\ d-1-5k,\ d-1-6k,\ d-4-10k). \]

Call a power active if its exponent is nonnegative. The slowest-decaying exponent is \(E_1\), which stays nonnegative up to \(k=\lfloor(d+1)/3\rfloor\). That’s about \(d/3\) odd denominators, and we divide just once for each one. Even the largest modulus is only \(2d/3+O(1)\), compared with about \(d\) for Bellard or Huvent, and \(2d\) for the original BBP formula.

As for the remainders \(r_j=2^{E_j}\bmod N\), notice that the middle two exponents differ by \(k\). If we already have \(r_3\) and \(x=2^k\bmod N\), then \(r_2\) is just \(xr_3\bmod N\). In fact, we can step from the smallest exponent up to the largest:

\[ r_4 \;\xrightarrow{\;\times\,8x^4\;}\; r_3 \;\xrightarrow{\;\times\,x\;}\; r_2 \;\xrightarrow{\;\times\,4x^2\;}\; r_1 \pmod N. \]

Start at the smallest active power. We pay for one full exponentiation to get it and one to get \(x\); the rest are a handful of multiplications. Past \(k\approx d/5\) only \(E_1\) is active, so don’t bother computing \(x\).2 That’s two exponentiations for the first \(d/5\) denominators and one for the remaining \(d/3-d/5\), or about \(8d/15\) altogether.

Sharing work across denominators

So far we’ve shared exponentiations among terms with the same denominator. We can also share them across denominators. We show two ways of doing this. The simpler way is to pair \(M\) with \(3M\), which saves a constant fraction of the work and needs only a few words of memory. With a sieve, we can go further: split each fraction into terms with prime-power denominators, then add up the numerators for each such power. A well-implemented sieve uses asymptotically more working memory than pairing, but its total running time is asymptotically better.

Grouping by denominator pairing

So far we’ve paid for one division by 13 and another by 39. Call the signed sums of their active powers \(A\) and \(B\). Since 39 is three times 13, their combined contribution is

\[ \frac{A}{13}+\frac{B}{39}=\frac{3A+B}{39}. \]

We only want the fractional part, so we can compute both numerators modulo 39, take the remainder of \(3A+B\), and divide by 39 just once.

Now consider the step powers. For 13 the index is 6; for 39 it’s 19. Since \(19=3\cdot6+1\), once we have \(x=2^6\bmod39\), we get the step for 39 by cubing and doubling: \(2^{19}\equiv2x^3\pmod{39}\).

In general, tripling a denominator \(M=2k+1\) changes its index from \(k\) to \(3k+1\). Substitute that index into the four exponents above to get the partner’s exponents. Now read the active exponents from both numerators in increasing order. The common \(d\) cancels in every gap, leaving a small multiple of \(k\) plus a constant. We need just two full exponentiations modulo \(3M\): one for the first power in the list and one for the step \(2^k\). Multiplication takes us up the rest of the list.

We never need to compute the step just for \(3M\). Its largest exponent, \(d-2-9k\), is smaller than the second exponent for \(M\), \(d-1-5k\). If \(3M\) has even one active power, \(M\) already has at least two.

We don’t want to pair 39 with 13 and then pair it again with 117. So we start pairs only at odd \(M\) not divisible by three. If \(3M\) has an active power, we take it with \(M\); otherwise we process \(M\) alone. Odd multiples of nine, like 117, stay unpaired.

The denominators that no longer need their own turn are precisely the odd multiples of three that aren’t multiples of nine. That’s two out of every nine odd denominators, both where we need one exponentiation and where we need two. Multiplying the counts above by \(7/9\) gives about \(7d/27\) divisions and \(56d/135\) full exponentiations, compared to \(2d/3\) of each for Huvent.

Grouping by prime powers

(Edit 25 Nov 2026: My first implementation of prime-power grouping built large sieves and didn’t vectorize well. While it did far fewer exponentiations, the pairing optimization was still much faster at the offsets I could reasonably compute, so I left this section out of the original post. Some discussion comments3 prompted me to revisit my implementation and reinstate this section.)

For a fixed digit window at bit offset \(d\), a segmented sieve can reduce the work from \(O(d\log d)\) to \(O(d\log\log d)\) word operations, at the cost of \(O(\sqrt d)\) bits of working space instead of \(O(\log d)\).

We start with the same boxed formula for \(\pi\), multiply by \(2^d\), and sum the terms with negative exponents as before. Call that tail \(T_d\). What changes is how we collect the remaining fractions. Take the signed numerators \(A\) and \(B\) over 13 and 39. The \(M\)-\(3M\) paired loop puts both over 39. The sieve goes the other way: it splits \(1/39\) into fractions over 3 and 13.

For digit extraction we only need the split to hold modulo one: the two sides can differ by an integer. Writing \(r/3+s/13\) back over 39, that means its numerator \(13r+3s\) must equal 1 modulo 39. Modulo 3, the \(3s\) term drops out and we get \(r\equiv1\pmod 3\). Modulo 13, the \(13r\) term drops out and we get \(3s\equiv1\pmod{13}\), so \(s=9\) works. Since 3 and 13 are coprime, the Chinese remainder theorem tells us that matching both remainders is enough to match modulo 39.

Indeed, \(1/3+9/13=40/39\), exactly one too large. Using \(-4\) instead of 9 subtracts that one and gives \(1/39=1/3-4/13\). Multiply by \(B\) and add \(A/13\), and we get

\[ \underbrace{\frac{3A+B}{39}}_{\text{paired loop}} = \frac{A}{13}+\frac{B}{39} = \underbrace{\frac{A-4B}{13}+\frac{B}{3}}_{\text{prime-power grouping}}. \]

So the fraction over 39 contributes \(-4B\) to the numerator over 13. Fractions over 65 and 91 also contribute there. To split any \(B/M\), write \(M\) as a product of (coprime) prime powers. For each such factor \(q\), put \(u=M/q\). When we put \(r/q\) back over \(M\), its numerator becomes \(ur\). The other fractions in the split all pick up a factor of \(q\) in their numerators, so we just need \(ur\equiv B\pmod q\). Since \(u\) and \(q\) are coprime, \(r=Bu^{-1}\bmod q\) is the numerator to add over \(q\).

We don’t need to evaluate \(A\) and \(B\) before splitting them. Each shifted power has the form \(2^{d+b}\). Modulo an odd prime power \(q\), we can factor out \(2^d\) even when \(b\) is negative, since 2 has an inverse. Let \(C_q(d)\) be the sum, modulo \(q\), of the coefficients left after factoring out \(2^d\). Writing braces for the fractional part, we get

\[ \{2^d\pi\} = \left\{T_d+\sum_q \frac{2^d C_q(d)\bmod q}{q}\right\}, \]

where \(q\) runs over the prime powers in the active denominators. One computation of \(2^d\bmod 13\) serves every contribution over 13, but to get that saving we have to find the contributing multiples and assemble their coefficient.

Notes on a high-performance implementation

Here is how far into \(\pi\) each method gets per expensive arithmetic operation, with the offset \(d\) measured in bits:

Formula Bits per full mod. exp. Bits per division
BBP, term by term 4/4 = 1.00 4/4 = 1.00
Euler, term by term 5/4 = 1.25 5/4 = 1.25
Bellard, term by term 10/7 ≈ 1.43 10/7 ≈ 1.43
Huvent, term by term 12/8 = 1.50 12/8 = 1.50
This post (\(M\)-\(3M\)) 135/56 ≈ 2.41 27/7 ≈ 3.86
This post (primes) \(\Theta(\log d)\) \(\Theta(\log d)\)

I implemented the last three methods using AVX-512 IFMA. Here are some benchmarks for extracting 12 hex digits on my Ryzen AI Max+ PRO 395, including sieve setup for the primes column. Both “% faster” columns are relative to Huvent.

Hex digits skipped Threads Huvent \(M\)-\(3M\) % faster Primes % faster
1,000,000 1 10.9 ms 6.24 ms +74.8% 4.70 ms +132.3%
100,000,000 1 1.23 s 731 ms +68.4% 273 ms +351.1%
1,000,000 32 4.03 ms 3.73 ms +8.3% 3.76 ms +7.2%
100,000,000 32 63.0 ms 39.6 ms +59.1% 16.2 ms +290.3%
1,000,000,000 32 678 ms 416 ms +62.8% 119 ms +468.5%
1,000,000,000,000 32 14m 6s 8m 41s +62.3% 2m 32s +456.2%

SIMD with paired denominators

Returning to the pair 13 and 39, while 39 is active, I never reduce modulo 13: changing the numerator for 13 by a multiple of 13 changes its tripled contribution by a multiple of 39. So I do all the squaring and multiplying modulo 39. Since 39 is odd, I can compute its inverse modulo a power of two once and reuse it for every Montgomery multiplication in the pair. I triple the numerator for 13, add the one for 39, and convert back from Montgomery form just once for the final division.

There’s a nice trick inside each exponentiation, too. Suppose a Montgomery reduction leaves \(-14\) modulo 39. Normally I’d add 39 to get 25. But if I’m going to square it next, 14 is just as good: \(14^2\equiv25^2\pmod{39}\). Even if the current exponent bit calls for doubling first, the next square still erases the sign. So for all but the last bit, I use vector absolute values instead of correcting the sign. On the last bit I do the usual reduction, since the numerator needs the actual residue rather than its negative. That change made the exponentiation loop about 8% faster on Zen 5.

Each vector lane handles a different odd modulus. I batch moduli with the same set of active powers so that one lane doesn’t sit idle while another steps through three extra residues. The hardware multiplies 52-bit inputs, so the largest modulus matters: ours is about \(2d/3\), compared with \(d\) for Huvent. That lets us reach about 50% farther into \(\pi\) before we need wider arithmetic.

SIMD with prime powers

Each worker sieves a 32 KiB block of odd numbers at a time. For small sieving primes the positions to cross out repeat, so I OR their bit masks into the block a word at a time. For the other sieving primes I keep track of the next multiple to cross out. If a prime skips whole blocks, I put it in a bucket for the next block it hits. That way I don’t have to scan the whole list of sieving primes for every block. The primes left in the block go to the arithmetic loop, one prime \(p\) per vector lane.

Let \(L\) be the largest active denominator. If \(p>L/17\), its only possible odd cofactors are \(1,3,\ldots,15\). Primes for which the same cofactors occur in each of the four sums share a rational coefficient up to a sign. I batch those primes together: eight vectors of eight lanes can follow the same exponent bits, each lane reducing modulo its own prime. There’s no loop over cofactors in this batch. At a billion hex digits skipped, about 93% of the primes take this path.

For the medium-sized primes, each lane keeps a running fraction \(a/b\) modulo \(p\). To add \(v/u\), it forms \((au+bv)/(bu)\) rather than computing an inverse for every \(u\). It only needs the final denominator’s inverse, and the squarings for that inverse can be shared with the query power. I handle the smallest primes and higher powers like \(13^2\) in scalar code.

A pedagogical Common Lisp implementation

This is a pedagogical implementation of the algorithm described in this post, including the \(M\)-\(3M\) pairing optimization and the prime-powers optimization. The code is otherwise not optimized; a proper implementation would be multithreaded and vectorized, including the aforementioned SIMD optimizations.

We start with some basic arithmetic utilities.

(defun odd-primes-through (limit)
 (let ((marked (make-array (1+ limit) :element-type 'bit
 :initial-element 0)))
 (loop :for p :from 3 :to limit :by 2
 :when (zerop (bit marked p))
 :collect p :and :do
 (loop :for m :from (* p p) :to limit :by (* 2 p)
 :do (setf (bit marked m) 1)))))

(defun pow2-mod (e q)
 (loop :with r := 1
 :for n := (abs e) :then (ash n -1)
 ;; For odd q, (q+1)/2 is the inverse of 2.
 :for base := (if (minusp e) (/ (1+ q) 2) 2)
 :then (mod (* base base) q)
 :while (plusp n)
 :when (oddp n) :do (setf r (mod (* r base) q))
 :finally (return r)))

(defun inverse-mod (u q)
 ;; Euclid's algorithm, tracking a = x*u and b = y*u modulo q.
 (loop :with a := q :and b := (mod u q)
 :with x := 0 :and y := 1
 :until (zerop b)
 :do (multiple-value-bind (quotient remainder) (floor a b)
 (psetf a b
 b remainder
 x y
 y (- x (* quotient y))))
 :finally (assert (= a 1))
 (return (mod x q))))

Each triple below describes one power in the boxed formula: its exponent is shift - slope*k, and its sign flips every run terms.

;; Numerator terms from the boxed formula.
;;
;; Each (shift slope run) describes one of the four powers over 2*k + 1.
;; Its exponent is shift - slope*k; its sign starts positive and flips
;; every run terms. For example, (1 3 2) gives 2^(1 - 3*k) with signs
;; +,+,-,-,+,+,-,-,... starting at k = 0.
(defvar *pi-numerator-terms*
 '(( 1 3 2)
 (-1 5 2)
 (-1 6 1)
 (-4 10 1)))

(defun term-sign (k run)
 (if (evenp (floor k run)) 1 -1))

(defun last-head-denominator (d)
 (1+ (* 2 (floor (1+ d) 3))))

Next, we implement the paired-head function, which calculates the head using the \(M\)-\(3M\) optimization. For \(M=2k+1\), active-powers builds a short list of triples (s b w), each representing \(w\,2^{d+b-sk}\). If we pair \(M\) with \(3M\), the terms for \(M\) get a weight of three. The partner’s index is \(3k+1\), so its exponent becomes \(d+(\text{shift}-\text{slope})-3\,\text{slope}\,k\). Now both sets of powers are written in terms of the same \(k\).

(defun active-powers (d k pairedp)
 (let ((terms nil))
 (flet ((add-power (s b w)
 (when (>= (+ d b) (* s k))
 (push (list s b w) terms))))
 (loop :for (shift slope run) :in *pi-numerator-terms*
 :do (add-power slope shift (* (if pairedp 3 1) (term-sign k run)))
 (when pairedp
 (add-power (* 3 slope) (- shift slope)
 (term-sign (1+ (* 3 k)) run)))))
 ;; For these terms, descending slope gives ascending exponent.
 (sort terms #'> :key #'first)))

(defun paired-fraction (d m pairedp)
 (let ((k (floor m 2))
 (q (if pairedp (* 3 m) m)))
 (destructuring-bind ((s b w) &rest more) (active-powers d k pairedp)
 (loop :with r := (pow2-mod (- (+ d b) (* s k)) q)
 :with total := (* w r)
 :with x := (when more (pow2-mod k q))
 :for (next-s next-b weight) :in more
 :for factor := (ash (expt x (- s next-s)) (- next-b b))
 :do (setf r (mod (* r factor) q)
 s next-s
 b next-b)
 (incf total (* weight r))
 :finally (return (/ (mod total q) q))))))

(defun paired-head (d)
 (loop :with limit := (last-head-denominator d)
 :for m :from 1 :to limit :by 2
 :for coprimep := (not (zerop (mod m 3)))
 :when (or coprimep (zerop (mod m 9)))
 :sum (paired-fraction d m (and coprimep (<= (* 3 m) limit)))))

The factor in that loop is just the step from one exponent to the next: \(x^{s-s'}2^{b'-b}\), where \(x=2^k\bmod q\). If only one power is active, we never compute \(x\). If both 13 and 39 are active, the entire loop runs modulo 39 and ends with one division. paired-head then skips 39 when it reaches it; 9, on the other hand, is processed on its own.

Next, we implement the prime-head function, which calculates the head using the prime-powers optimization. For a particular prime power \(q=p^e\), visit the denominators \(qu\) for \(u=1,3,5,\ldots\), skipping multiples of \(p\). For instance, \(39=13\cdot3\) belongs in the group for 13, but \(169=13\cdot13\) belongs in the group for 169 instead. As \(u\) advances by two, \(k=(qu-1)/2\) advances by \(q\). That’s why we can update the unshifted power weight by a multiplication each time.

(defun group-coefficient (d p q)
 (loop :with first-k := (floor q 2)
 :for (shift slope run) :in *pi-numerator-terms*
 :for last-k := (floor (+ d shift) slope)
 :when (<= first-k last-k)
 :sum (loop :with count := (1+ (floor (- last-k first-k) q))
 :with weight-period := (lcm (* 2 run)
 (/ (1- p) (gcd slope (1- p))))
 :with jump := (pow2-mod (- (* slope q)) q)
 :for k :from first-k :by q
 :for u :from 1 :by 2
 :for weight := (pow2-mod (- shift (* slope first-k)) q)
 :then (mod (* weight jump) q)
 ;; Over q weight periods, opposite cofactors'
 ;; inverses cancel modulo q.
 :repeat (mod count (* q weight-period))
 :unless (zerop (mod u p))
 :sum (* (term-sign k run) weight (inverse-mod u q)))
 :into c
 :finally (return (mod c q))))

(defun prime-head (d)
 (let ((limit (last-head-denominator d)))
 (loop :for p :in (odd-primes-through limit)
 :sum (loop :for q := p :then (* q p) :while (<= q limit)
 :sum (/ (mod (* (pow2-mod d q)
 (group-coefficient d p q))
 q)
 q)))))

prime-head computes \(2^d\bmod q\) once per group. This version of group-coefficient also uses modular powers to initialize weight and jump, but not for every multiple of \(q\). The denominator 1 needs no group: its active terms are integers.

Finally, we implement the tail, which is the same regardless of optimization. If we stop a family when its exponent drops below \(-B\), the first omitted term has magnitude at most \(2^{-B-1}\) and each following term is at most one eighth as large. So \(4\cdot2^{-B}\) bounds the total error from all four tails. If that could change the last hex digit, we take a few more terms.

(defun tail-sum (d bits)
 (loop :for (shift slope run) :in *pi-numerator-terms*
 :for first-k := (max 0 (1+ (floor (+ d shift) slope)))
 :sum (loop :for k :from first-k
 :for e := (- (+ d shift) (* slope k))
 :while (>= e (- bits))
 :sum (/ (* (term-sign k run) (expt 2 e)) (1+ (* 2 k))))))

(defun pi-hex-digits (skip &key (width 12) (head #'prime-head))
 (check-type skip (integer 0 *))
 (check-type width (integer 1 *))
 (let* ((d (* 4 skip))
 (scale (expt 16 width))
 (h (funcall head d)))
 (loop :for bits :from (+ (* 4 width) 8) :by 16
 :for value := (+ h (tail-sum d bits))
 :for radius := (* 4 (expt 2 (- bits)))
 :for lo := (floor (* scale (- value radius)))
 :for hi := (floor (* scale (+ value radius)))
 :when (= lo hi)
 :return (format nil "~v,'0X" width (mod lo scale)))))

skip counts hex digits after the point, not bits. :width defaults to 12 digits and :head defaults to #'prime-head. Use :head #'paired-head to select pairing:

CL-USER> (pi-hex-digits 100 :width 8 :head #'prime-head)
"29B7C97C"
CL-USER> (pi-hex-digits 100 :width 8 :head #'paired-head)
"29B7C97C"

  1. Craig-Wood’s implementation evaluates 21 fractions separately for every 30 bits of offset. ↩︎

  2. There’s a way to thin out the far end of the loop even more. At \(j=4m+3\), the real and imaginary parts of \((1+i)^j\) are opposites. Add the real part of each logarithm and the two slow powers cancel for \(N\equiv3\pmod4\). We still have to subtract the real logarithms we added, using series for \(\log(1+2^{-2})\), \(\log(1+2^{-3})\), and \(\log(1-2^{-4})\). That leaves half as many moduli above \(d/2\), at the cost of more streams of powers to juggle below it. ↩︎

  3. Thanks to Doug Coleman and Prajay Basu for sharing their explorations of this algorithm. ↩︎

vindarel — &#127909; Lem editor quick tour (screencast): a modern Emacs? + Lem on WASM in the browser

· 12 days ago

Lem is evolving at a good rhythm.

I am reviewing, testing and merging pull requests nearly everydays.

It has a webview interface, multiple cursors, multiple major modes (interactive markdown code blocks), code folding (for Lisp sources), remote file editing (Tramp), a file tree and a directory mode (à la Dired), a transient pop-up window showing all available keybindings, a built-in tutorial, a customizable dashboard, a spell checker, a templating extension, AI integration, a Git interface (functional but lacking interactive rebase), that you can easily call from the CLI, also git gutters, org-mode support is coming, it supports many programming languages with (or without) LSP and tree-sitter (great Typst mode, that’s another excuse to use Lem), a terminal using libvterm, ... and I am not giving a full list of new features. You can follow along on reddit.

Here’s a quicktour in 7 minutes, not even showing everything either:

The day after I recorded my video, cxxxr announced his vibe-coded Common Lisp implementation on WASM (clysm)that is able to run Lem in the browser:

So that’s the second implementation of CL on WASM after miricl, or the third, with ECL’s ongoing work.

We also have pull requests, by a regular contributor, adding a SDL3 front-end, also vibe-coded, based on the existing (deprecated) SDL2 front-end.

So is Lem slop?

Depends on your definition I guess. It was developed for 10 years by hand, by cxxxr and the early contributors. Today a certain percent of the code-base was touched or done with LLMs.

I saw that they were first used to add language definitions, a tedious thing, based on the existing hand-designed foundations. Then contributors brought bug fixes and performance improvements. Then came new features. Tramp or the spell checker for example. I reviewed them, they are short and idiomatic. So if that was your concern I am not yet worried by code quality.

However, earth is burning.


🕊

vindarel — CSV parsing in Common Lisp, data manipulation by columns with data frames

· 22 days ago

Parsing CSV files is a common task. What are our options? We’ll start with cl-csv, add the data-table library, and present lisp-stat’s data frames.

This is another contribution to the Common Lisp Cookbook so you should read it there as this is where it will get updates.

With a very simple dataset we could split CSV lines manually (subseq, split-sequence, str:split, cl-ppcre...) but when a column contains the separator, a library starts to be useful.

And a library will be even more so to help us manipulate columns by name, to use tabular data structures, to automatically infer the columns’ types, and more.

I recommend:

  • for simple use, try cl-csv
  • if you’ll do statistics or want a good dataframes library, go for lisp-stats
  • to work with large datasets, see cl-csv’s :row-fn argument.
  • for the fastest parsing, maybe fare-csv, or DuckDB with cl-duckdb, which can also ingest much more file formats than CSV, including Excel.
Long time no see o/ I'm lisping more than ever though. CIEL got new features, I am the one reviewing, testing and merging Lem pull requests (it got so many features... you can follow on reddit), I am busy but I commit to my DB admin dashboard once in a while, I maintain and extend my apps in production... In the CL world so many things happened (that will be a blog post in January), for instance we got new good editors. I want to record videos about them. In the meantime, grab my course with this coupon :] (it's the best price I can offer). Thank you!

Table of Contents

Introduction: our test files

Let’s work together with this simple CSV file, persons.csv:

Alice,7,1
Bob,77,0

The separator is , (often the default in libraries).

For simplicity, the file doesn’t contain a headers row.

This second file, persons2.csv, contains headers:

name,age,lisper
Alice,7,1
Bob,77,0

Parsing with cl-csv

The cl-csv library is on Quicklisp.

(ql:quicklisp "cl-csv")

It allows to parse data from a string, from a file, or from any stream.

It may not be the fastest, but it has a decent set of quality-of-life features.

Please go read its README, as we don’t illustrate some of its features here. For example, it supports multiline quoted data, we can set the quote character, it has good error messages (line and column number, char index), etc.

For reference, this is the function signature of cl-csv:read-csv (C-c-s on Slime):

(cl-csv:read-csv stream-or-string :csv-reader csv-reader
                                             :row-fn row-fn
                                             :map-fn map-fn
                                             :data-map-fn data-map-fn
                                             :sample sample
                                             :skip-first-p skip-first-p
                                             :separator *separator*
                                             :quote *quote*
                                             :escape *quote-escape*
                                             :unquoted-empty-string-is-nil *unquoted-empty-string-is-nil*
                                             :quoted-empty-string-is-nil *quoted-empty-string-is-nil*
                                             :trim-outer-whitespace *trim-outer-whitespace*
                                             :newline *read-newline*
                                             :escape-mode *escape-mode*)

Parsing from a string

To parse from a string, just use cl-csv:read-csv:

(cl-csv:read-csv "Alice,7,1
Bob,77,0")
;; =>
(("Alice" "7" "1") ("Bob" "77" "0"))

It returns a list of lists, values are all strings.

Parsing from a file

Also use cl-csv:read-csv but give a pathname as argument, not only the filename as a string.

(cl-csv:read-csv #P"persons.csv")
;; =>
(("Alice,7,1") ("Bob,77,0"))

What happens if you omit the #P?

(cl-csv:read-csv "persons.csv")
;; =>
(("persons.csv"))

this looks strange and no, there is no bug ;)

To parse from a stream, see the library’s documentation.

Using another separator

Is ; the columns separator? Use cl-csv:read-csv’s :separator argument, or the global cl-csv:*separator* parameter.

For a Tab, use #\Tab.

(defparameter *csv-string* "Alice;7;1
Bob;77;0")

(cl-csv:read-csv *csv-string* :separator #\;)

;; OR

(let ((cl-csv:*separator* #\;))
  (cl-csv:read-csv *csv-string*))

Skipping the first row of headers

With cl-csv, use :skip-first-p.

However, we’ll use this row of headers as soon as we work with dataframes.

(cl-csv:read-csv "name,age,lisper
Alice,7,1
Bob,77,0"
 :skip-first-p t)

Returning a list of objects

So far, we got a list of lists with raw values as strings. We can do whatever we want with them. cl-csv has a :map-fn argument that we can use to create an object while parsing each row.

Let’s re-use our class definition from the CLOS chapter:

(defclass person ()
  ((name :initarg :name :initform "")
   (age :initarg :age :initform nil)
   (lisper :initarg :lisper :initform nil)))

We can parse our CSV and return a list of objects at once:

(cl-csv:read-csv #p"persons.csv"
  :map-fn (lambda (values)
             (make-instance 'person :name (nth 0 values)
                                    :age (parse-integer (nth 1 values))
                                    :lisper (if (equal "1" (nth 2 values)) t nil))))

Observe that:

  • we had to parse the age from a string to an integer ourselves
  • our file doesn’t have a headers row.

Streaming reads (for large files)

cl-csv provides the :row-fn parameter, that does something with each row and doesn’t return them. This allows us to work with large datasets.

In this example, the :row-fn function has side-effects after each row was read and passed to it. Our function returns a result, the mean of ages.

(let ((sum-ages 0)
      (nb-ages 0))
  (cl-csv:read-csv #p"persons.csv"
                   :row-fn (lambda (values)
                             (incf sum-ages (parse-integer (nth 1 values)))
                             (incf nb-ages)))
  ;; Age mean:
  (/ sum-ages nb-ages))

Using cl-csv’s reader information for debugging

cl-csv makes efforts to tell us where it is at its parsing. Here’s where to find the bits of information that will help us during debugging.

In this dummy example, we’ll observe cl-csv’s hints:

;; this is uncomplete CSV, parsing will raise an error:
(cl-csv:read-csv "Alice,7,1
Bob,77,0
Oh?")

;; =>

The value
  NIL
is not of type
  STRING
when binding STRING
   [Condition of type TYPE-ERROR]

Restarts:
 0: [RETRY] Retry SLIME REPL evaluation request.
 1: [*ABORT] Return to SLIME's top level.
 2: [ABORT] Exit debugger, returning to top level.

Backtrace:
  0: (SB-IMPL::PARSE-INTEGER10 NIL 0 NIL NIL) [external]
  1: ((LAMBDA (VALUES)) ("oh?"))
  2: (CL-CSV::READ-CSV-WITH-READER #P"persons.csv" :CSV-READER NIL :ROW-FN #<FUNCTION (LAMBDA (VALUES)) {1203B956DB}> :MAP-FN NIL :DATA-MAP-FN NIL :SKIP-FIRST-P NIL)
      Locals:
        #:.DEFAULTING-TEMP. = NIL
        CSV-READER = #<CL-CSV::CSV-READER LINE-IDX:2 CHARACTER-LINE-IDX:4 CHARACTER-IDX:23 "" {1203B99343}>

        ^^^^^ let's see more about this READER object.

        DATA-MAP-FN-P = NIL
        IN-STREAM = #<SB-SYS:FD-STREAM for "file /home/vindarel/cl-cookbook/persons.csv" {1203B96553}>
        MAP-FN-P = NIL
        #:NEW3 = #<FUNCTION (LAMBDA (VALUES)) {1203B956DB}>
        #:NEW5 = NIL
        #:NEW7 = NIL
        #:NEW9 = NIL
        ROW-FN-P = T
        STREAM-OR-STRING = #P"persons.csv"
  3: (CL-CSV:READ-CSV #P"persons.csv" :ROW-FN #<FUNCTION (LAMBDA (VALUES)) {1203B956DB}>)

We don’t see everything. Click or press Enter on the CSV-READER that is on the 2nd backtrace:

#<CL-CSV::CSV-READER {1203B99343}>
--------------------
Class: #<STANDARD-CLASS CL-CSV::CSV-READER>
--------------------
 Group slots by inheritance [ ]
 Sort slots alphabetically  [X]

All Slots:
[ ]  AFTER-QUOTED?      = NIL
[ ]  BUFFER             = ""
[ ]  CHARACTER-IDX      = 23         <------------ useful: character index in the file
[ ]  CHARACTER-LINE-IDX = 4
[ ]  DATA-MAP-FN        = CL-CSV::MAP-EMPTY-STRING-TO-NIL
[ ]  ENTRIES            = #(#<CL-CSV::READ-DISPATCH-TABLE-ENTRY {1203B98F93}> #<CL-CSV::READ-DISPATCH-TABLE-ENTRY {1203B99033}> #<CL-CSV::READ-DISPATCH-TABLE-ENTRY {1203B990D3}> #<CL-CSV::READ-DISPATCH-TABLE-ENTRY {1203B99173}> #<CL-CSV::READ-DISPATCH-TABLE-ENTRY {1203B99213}> #<CL-CSV::READ-DISPATCH-TABLE-ENTRY {1203B992B3}>)
[ ]  LINE-DATA          = #()
[ ]  LINE-IDX           = 2           <------------- useful: line index
[ ]  MAP-FN             = NIL
[ ]  PARSE-STREAM       = #<SB-SYS:FD-STREAM for "file /home/vindarel/cl-cookbook/persons.csv" {1203B96553}>
[ ]  READING-QUOTED?    = NIL
[ ]  ROW-FN             = #<FUNCTION (LAMBDA (VALUES)) {1203B956DB}>
[ ]  ROWS               = #()
[ ]  SKIP-ROW?          = NIL

[set value]  [make unbound]

Knowing the line causing an error and the file position is useful.

cl-csv and data-table: column names, column types, columns manipulation

data-table is a library by the same authors that brings a data structure that represents our CSV data.

A data table has rows of data, associates names to the columns, and guesses columns types.

Then, we can access values by row and column names, and manipulate columns (add data, take a substract etc).

We link cl-csv and data-tables together with the system cl-csv-data-table (defined in cl-csv).

(ql:quickload '("cl-csv" "data-table" "cl-csv-data-table"))

You don’t need to go read its README, as it is poorly documented (only in tests).

We’ll use the second CSV file, persons2.csv.

Let’s parse it:

(cl-csv:get-data-table-from-csv #p"persons2.csv")
;; =>
#<DATA-TABLE:DATA-TABLE {1205D151C3}>

This returns a DATA-TABLE object. What is it? We can inspect it:

(inspect *)

The object is a STANDARD-OBJECT of type DATA-TABLE:DATA-TABLE.
0. COLUMN-NAMES: ("name" "age" "lisper")
1. COLUMN-TYPES: (STRING INTEGER INTEGER)
2. ROWS: (("Alice" 7 1) ("Bob" 77 0))

We observe:

  • the data-table used our headers row
  • the columns’ types were inferred: “name” is a string, “age” and “lisper” are integers.
  • in each row, the “age” and “lisper” fields were parsed to an integer.

Let’s save our result to a parameter:

(defparameter *dt* **)

Get all rows with:

(data-table:rows *dt*)

Instead of accessing a column by its index, you can access it by its name.

Use data-table:data-table-value dt &key row row-idx col-name col-idx.

For example, what is the “name” of the first row?

(csv:data-table-value *dt* :row-idx 0 :col-name "age")
;; => 7

The library has more functions to manipulate columns and data-tables. We give them as a reference, and then we’ll see how lisp-stat does it.

data-table:number-of-rows and data-table:number-of-columns

data-table-to-plists, plists-to-data-table

Add columns together with (csv:add-column dt column-name [default] [column-type] [index]).

Select columns with (csv:select-columns table column-names) to create a new data-table.

In this example, we create a new data-table object with only 2 columns. We also inverted their order.

(csv:select-columns *dt* '("age" "name"))
;; =>
#<DATA-TABLE:DATA-TABLE {1203F88213}>
CL-USER> (inspect *)

The object is a STANDARD-OBJECT of type DATA-TABLE:DATA-TABLE.
0. COLUMN-NAMES: ("age" "name")
1. COLUMN-TYPES: (INTEGER STRING)
2. ROWS: ((7 "Alice") (77 "Bob"))
> q

overlay-region new dt :col-idx col-idx :row-idx row-idx): “puts all values from new-dt into dt starting at row-idx col-idx”.

make-sub-table parent :uri uri :lri lri :uci uci :lci lci:

Make a new data table from a subset of another data-table
   lci - low column index
   uci - upper column index (as per subseq 1 beyond the col you want)
   lri - low row index
   uri - upper row index (as per subseq 1 beyond the row you want)

Write a data-table to a file (or any stream) with (data-table-to-csv dt &optional stream)

All this is good, but today lisp-stat does this, and more.

lisp-stat’s Data Frame

lisp-stat is a powerful library.

Lisp-Stat provides a statistical computing engine comparable to R, Python, Julia and Matlab. Its major differentiators are a true REPL based development environment, high performance and a single binary image that can be moved through the devops pipeline in a secure, safe and manageable way.

It integrates with Jupyter notebooks, to Quarto, it can load R datasets...

It’s pretty good and actively used and developed.

It interests us for its Data Frame. You should go read its documentation ;)

Let’s load the library:

(ql:quickload :lisp-stat)

We’ll give a brief showcase. For this, we’ll go to the ls-user package. It is “the package for you to do statistics work”.

(in-package :ls-user)

We can read a CSV file with read-csv. This function is actually not the one we used so far with cl-csv, it is a wrapper around fare-csv.

So, using another separator is different, use fare-csv:*separator*.

(defparameter *persons-df* (read-csv #p"persons2.csv"))
;; => *PERSONS-DF*

It is important we used our file persons2.csv which contains the first row with column names.

We can start working with our data.

How do we get all names of our dataset? Simply like this:

LS-USER> (column *persons-df* 'name)
#("Alice" "Bob")

That’s already interesting, isn’t it?

Observe that: - the result is not a list, it is an array.

lisp-stat has a notation trick to access data in an even shorter way. For this, we need to define an “environment” with defdf:

LS-USER> (defdf persons (read-csv #p"persons2.csv"))
;; => #<DATA-FRAME (2 observations of 3 variables)>

Observe that: - we deliberately didn’t use “*earmuffs*” around “persons” - the environment already gives us information: it saw 2 rows and 3 columns.

Now, we can get all names simply with:

LS-USER> persons:name   <----- you can use auto-completion, of course.
;; => #("Alice" "Bob")

all ages:

LS-USER> persons:age
;; => #(7 77)

We can inspect the shape of our data:

LS-USER> (head persons)

;;   NAME  AGE LISPER
;; 0 Alice   7      1
;; 1 Bob    77      0

Using another function, select, we can get all ages with:

LS-USER> (select persons t 'age)
;;                      ^^^ take the age of all rows

But with select we can get a subset of values:

LS-USER> (select persons '(0 1) 'age)
;;                         ^^^ our subset (it's all our data lol)
;; => #(7 77)

We can get values of some columns:

LS-USER> (columns persons '(age name))
;; => #(#(7 77) #("Alice" "Bob"))

We can get a high-level description of our dataset:

LS-USER> (describe persons)
PERSONS
  A data-frame with 2 observations of 3 variables

Variable | Type | Unit | Label
-------- | ---- | ---- | -----------
NAME     | NIL  | NIL  | NIL
AGE      | NIL  | NIL  | NIL
LISPER   | NIL  | NIL  | NIL

This shows that the columns’ types were not inferred. Can we fix this?

LS-USER> (heuristicate-types persons)
NIL

LS-USER> (describe persons)
PERSONS
  A data-frame with 2 observations of 3 variables

Variable | Type    | Unit | Label
-------- | ----    | ---- | -----------
NAME     | STRING  | NIL  | NIL
AGE      | INTEGER | NIL  | NIL
LISPER   | BIT     | NIL  | NIL

Yes, now they are.

We can now manipulate columns: add, remove, rename, replace, transform... as well as rows: add, count, loop over (do-rows), map into, mask, filter...

Everything is in lisp-stat’s documentation!

Utilities

We saw how to do that with lisp-stat’s head function.

We have another solution with the cl-ansi-term library.

(ql:quickload '("cl-ansi-term"))

Its global nickname is term (warn: global nicknames are now legacy, prefer package-local nicknames).

We use term:table to print our tabular data.

(let ((csv (cl-csv:read-csv #p"persons2.csv")))
  (term:table csv))

;; =>
+-----+---+------+
|name |age|lisper|
+-----+---+------+
|Alice|7  |1     |
+-----+---+------+
|Bob  |77 |0     |
+-----+---+------+

It has a few more options. With many columns, you could display only a chosen set of columns. You can style cells programmatically, etc.

See also

  • acknowldegment: read CSV files in CL on dev.to
  • auto-text, automatic detection for text files (encoding, end of line, column width, csv delimiter etc). inquisitor for detection of asian and far eastern languages.
  • CLAWK, an AWK implementation embedded into Common Lisp, to parse files line-by-line.
  • redditors’ feedback about duckdb, SBCL maintainer’s fast parsing snippet.

TurtleWare — Heavenly delights of hashing numbers under EQUALP

· 35 days ago

Some time ago I decided to dust off my fast generic function dispatch work for ECL. But before merging that, I decided to optimize the table-based dispatch to have a good measure of how much better or worse it is and that opened a whole can of worms, including a new implementation of hash tables and hash functions.

I know, that's a new level of traversing absurdly nested rabbit holes. There are two good outcomes of this:

  1. Hash tables and generic function dispatch will be much faster soon
  2. I got inspired to write another blog post pertaining to Common Lisp

Regarding the first point, here are a few bar graphs generated using polyclot, a work-in-progress McCLIM tool for plotting data (less is better):

cherry-picking.png

Figure 1: SLOT-ACCESS/READER - standard reader benchmark (work in progress).

htable-mixbag.png

Figure 2: HTABLE-MIXBAG - EQUALP benchmark with randomized keys.

htable-setrem.png

Figure 3: HTABLE-SETREM - benchmark for interleaved insert and remove.

htable-string.png

Figure 4: HTABLE-SMALL-STRING - EQUALP benchmark with short strings.

As for the second point, while working on hashing under various Common Lisp predicates, I decided to bite the bullet and fix a few ugly parts of ECL. Most notably consistent hashing of numbers under the predicate #'EQUALP. The topic is interesting enough to deserve a separate note. In this post I'm assuming binary floats (the float radix is two). This is the float representation used in ECL.

1. Hashing numbers - warmup

1.1. Recap: hash table tests and hash functions

A quick recap about Common Lisp and hash tables. The standard prescribes that conforming implementations must allow specifying the hash table tests EQ, EQL, EQUAL and EQUALP. The last test is interesting, because numbers with different representations are considered to be EQUALP when they are =. For example:

(equalp 1 1.0)           ; -> T
(equalp 1/2 0.5)         ; -> T
(equalp 1/3 (float 1/3)) ; -> NIL
(equalp 42 #C(42.0 0.0)) ; -> T

It is worth noting, that hashing can be lossy, but it can't be inconsistent with the test. In other words this is a conforming hash function under #'EQUALP:

;; (equalp 1 1.0)                        ; is true
;; (= (hash-equalp 1) (hash-equalp 1.0)) ; is true

(defun hash-equalp (x)
  (typecase x
    (real      42)
    (complex   (if (zerop (imagpart x))
                   (hash-equalp (realpart x))
                   13))
    (otherwise 15)))

While this function is not conforming, because there are objects that are the same under the test and have different hashes:

;; (equalp 1 1.0)                        ; is true
;; (= (hash-equalp 1) (hash-equalp 1.0)) ; is false

(defun hash-equalp (x)
  (typecase x
    (rational  1337)
    (float     7117)
    (complex   (if (zerop (imagpart x))
                   (hash-equalp (realpart x))
                   13))
    (otherwise 15)))

In other words, when two objects are equal under the supplied test, they must produce the same hash, but two objects having the same hash does not imply that they are equal under the supplied test.

Naive hashes, while conforming, miss the point. A good hashing function tries to produce different hashes for objects that are not equivalent under the predicate with a good bit distribution to ensure good hash table performance.

1.2. Recap: the numeric tower and mathematical equivalence

Common Lisp has a full numeric tower:

numeric-tower.png

Figure 5: Common Lisp numeric tower.

Note that when complex floats have specialized representation, then there may be multiple subtypes specialized to single-float, double-float etc. Numbers are #'= to each other when their value is mathematically the same, regardless of the underlying representation. That's a wonderful quality when you do math :-).

This quality is not so wonderful, when you want to produce good hashes under the predicate #'EQUALP (that boils down to #'= for numbers). We need to construct a function that will produce the same hashes with good quality for equal objects.

The biggest hurdle comes from the gap between representations of RATIONAL and FLOAT objects. Conventionally representations are

fixnum
a single word with a few bits chopped to fit the tag
bignum
an array of "limbs", that is parts of the integer (plus sign)
ratio
a pair of two integers
float
a pair of N-bit mantissa and K-bit exponent (plus sign)
(complex rational)
a pair of two rationals
(complex float)
a pair of two floats of the same type

Fixnums, bignums and ratios are disjoint under #'=. That leaves us with questions:

  1. When are two complex numbers mathematically equal?

    This one is easy. Two complex numbers are equal when their real parts are equal and their imaginary parts are equal.

  2. When are two floats mathematically equal?

    To resolve this question we can cast the float with smaller precision to the float with bigger one and compare bits. There is a gotcha in that -0.0 is not EQL to +0.0, but it is always = to it, so we should canonicalize zeros first.

  3. When is an integer mathematically equal to a float?

    When the float has no fractional part and integers are equal.

  4. When is a ratio equal by #'= to a float?

    This is the most interesting question. To answer it, we need to dive a bit deeper into float representation.

    Finite binary float values conceptually are represented as:

    (* sign mantissa (expt 2 exponent))

    This corresponds to dyadic rationals, that is rational numbers whose denominator is a power of two:

    (/ n (expt 2 k))

    In other words a float and a ratio may be equal only when the ratio is dyadic, otherwise the ratio value can't be represented as a binary float (this post assumes that we operate on binary floats - with radix=2).

That sums up the recap about mathematical equivalence and numeric tower in Common Lisp.

1.3. Establishing the baseline

The easiest, yet useless, approach is to always return a hash 42. It is adequate because that is the canonical answer to the most important question.

The easy and useful approach relies on the observation that hashing is lossy. All real numbers are coerced to a float precision and hashed. When the rational number does not fit in the float precision, then we hash its approximation. We need to remember to canonicalize -0.0 to +0.0 and to disable floating point exceptions for cases like overflows and underflows.

#define hash_single_float(h,v) hash_float((h), (double)(v))
#define hash_double_float(h,v) hash_float((h), (double)(v))

static inline void
hash_float(cl_hashstate *h, double v)
{
  if (v==-0.0) v=0.0;
  hash_data(h, &v, sizeof(v));
}

static inline void
hash_long_float(cl_hashstate *h, long double v)
{
  ECL_WITHOUT_FPE_BEGIN {
    hash_float(h, (double)(v));
  } ECL_WITHOUT_FPE_END;
}

#define hash_fixnum(h,x) hash_float((h),(double)ecl_fixnum(x))
#define hash_bignum(h,x) hash_rational((h),(x))
#define hash_ratio(h,x)  hash_rational((h),(x))

static inline void
hash_rational(cl_hashstate *h, cl_object x)
{
  ECL_WITHOUT_FPE_BEGIN {
    double v = ecl_to_double(x);
    hash_float(h, v);
  } ECL_WITHOUT_FPE_END;
}

This model is conceptually obvious, very maintainable, reasonably fast, and there are relatively few collisions under the usual workload. We pay for it in a few ways:

  1. Aesthetically it is not pleasing - crude even.
  2. "Relatively few collisions" applies only to toy examples, once we start using bigger integers and more precise ratios, the problem starts to show. For example 260 and 260+1 hash identically and that matters for 64bit IDs and timestamps.
  3. Performance-wise we drop the ball for integers and rationals – we convert numbers between formats even when we could hash only a chunk of memory.

This list is ranked by importance as I see it. The main reason I've kept digging deeper is that it was not to my taste. Then we had impracticality for serious workloads, finally microoptimizations. I believe that the general audience has these priorities in a reversed order.

2. Hashing numbers - round one

A harder but more precise way to hash numbers under the predicate #'EQUALP is to introduce canonicalization rules:

  1. Integers are hashed as integers

    In the case of FIXNUM we hash its value (a word without the tag) and in the case of BIGNUM we hash the sign and its limbs.

  2. Finite floats without the fractional part are hashed as integers

    Ensures INTEGER <-> FLOAT correspondence. We can't cast LONG-FLOAT to DOUBLE-FLOAT and then cast to integer, because we'd miss many BIGNUM values. Caveat: with this approach big floats may cons full bignums.

  3. Floats that are not integers are cast to DOUBLE-FLOAT and hashed

    Ensures X-FLOAT <-> Y-FLOAT correspondence. This approach is lossy for long floats if they have more bits than double floats, but simplifies the implementations because long double has a few "loose" bits that may differ between numbers with the same value.

    NaNs and infinities are hashed like other doubles because infinities are exact and NaN is never #'= to anything.

  4. Dyadic ratios are hashed as DOUBLE-FLOAT

    Ensures FLOAT <-> RATIO correspondence. For simplicity we don't try to determine whether RATIO is representable as DOUBLE-FLOAT – if it is too big or too small, it will be represented either as a 0 or as an infinity.

  5. Other ratios are hashed as pairs

    We hash the numerator and denominator separately.

  6. Complex floats with (ZEROP (IMAGPART X)) are hashed as (HASH (REALPART X))

    Because (= 3 #c(3.0 0.0)) we need to canonicalize (complex float) while rational complex numbers are canonicalized implicitly. Other complexes are hashed as pairs, that is we hash the real part and imaginary part separately.

This approach results in fewer collisions and is fairly straightforward. Here is the pseudocode:

(defun hash-equalp-number (state number)
  (typecase number
    (fixnum  (hash-word state number))
    (bignum  (hash-data state (signum number) (limbs number)))
    (float   (if (and (finitep number) (is-integer-p number))
                 (hash-equalp-number state (rational number))
                 ;; INV -0.0 and +0.0 are hashed as integers.
                 (hash-data state (coerce number 'double-float))))
    (ratio   (if (dyadic-ratio-p number)
                 ;; INV may produce infinity or zero (that's fine)
                 ;; Disable float overflow and underflow traps.
                 (hash-data state (coerce number 'double-float))
                 (progn
                   (hash-equalp-number state (numerator number))
                   (hash-equalp-number state (denominator number)))))
    (complex (if (zerop (imagpart number))
                 (hash-equalp-number state (realpart number))
                 (progn
                   (hash-equalp-number state (realpart number))
                   (hash-equalp-number state (imagpart number)))))))

2.1. Implementation bites

My initial implementation cast all floats to integers. When I was comparing ECL to other implementations I was wondering why we are so slow compared to others. The key insight came after the realization that randomized keys in the form (random 20.0) were collapsed to only 20 distinct hashes.

Fixing that and giving non-integer floats distinct hashes gave ECL the most noticeable boost on the HTABLE-MIXBAG benchmark (included at the beginning) - the new version is 100x faster than the old one.

While implementing a test suite that ensured that hashes for bignums, dyadic ratios, and corresponding floats matched, I've discovered a non-obvious bug pertaining to casting double floats to integers. The code looked like this:

if (d<=MOST_POSITIVE_FIXNUM && d>=MOST_NEGATIVE_FIXNUM) return to_fixnum(d);
else                                                    return to_bignum(d);

But the MOST_POSITIVE_FIXNUM value on x86-64 is 261-1. In other words, to represent this number exactly as a double, we need 61 significant bits. That's a shame because double has 53 significant bits, so MOST_POSITIVE_FIXNUM, when converted to double, rounds to 261 and that can't fit in a fixnum. After promotion the incorrect code is equivalent to:

if (d<=(1LL<<61) && d>=MOST_NEGATIVE_FIXNUM) return to_fixnum(d);
else                                         return to_bignum(d);

Oops, double is accidentally cast to fixnum when it is 261. That's clearly a problem! After finding the issue, the solution is easy. We need to find an exact double that is the boundary. Note that integers are implemented as two's complement, so the most negative fixnum was alright in our case:

double limit = ldexp(1.0, ECL_FIXNUM_BITS-ECL_TAG_BITS-1);
if (d<limit && d>=-limit) return to_fixnum(d);
else                      return to_bignum(d);

This fix is correct, yet it revealed another bug. But that's a different story to tell.

3. Hashing numbers - round two

The approach above is correct and nice, but has a few important flaws:

  • we cons a lot for big integer floats (2KB/float in the worst case)
  • there is a whole class of dyadic ratios that don't fit in long-float
  • long floats lose precision after cast to double, notably very small and very big values collapse to 0 and infinity

After the initial implementation it bugged me enough that I've decided to come up with a new hashing scheme for numbers under the predicate EQUALP. The rules are also simpler (at least conceptually):

  1. Dyadic rationals are hashed as tuples (sign, mantissa, exponent)
  2. Other numbers are hashed depending on their type (they are disjoint)

The representation [SIGN MANTISSA EXPONENT] does not require us to convert between types and it is very compact. Moreover it is very precise and doesn't produce unnecessary collisions. On the other hand it requires extra work to normalize tuples. Here is the pseudocode:

(defun hash-equalp-number (state number)
  (typecase number
    (integer
     (multiple-value-bind (s m e) (compute-integer-dyad number)
       (hash-dyad state s m e)))
    (float
     (multiple-value-bind (s m e) (compute-float-dyad number)
       (hash-dyad state s m e)))
    (ratio
     (if (dyadic-ratio-p number)
         (multiple-value-bind (s m e) (compute-ratio-dyad number)
           (hash-dyad state s m e))
         (progn
           (hash-datatype-tag state :ratio)
           (hash-equalp-number state (numerator number))
           (hash-equalp-number state (denominator number)))))
    (complex
     (if (zerop (imagpart number))
         (hash-equalp-number state (realpart number))
         (progn
           (hash-datatype-tag state :complex)
           (hash-equalp-number state (realpart number))
           (hash-equalp-number state (imagpart number)))))))

The implementation is a bit less straightforward because we now need to be able to compute mantissa from numbers. A few words about normalization:

  • sign is -1, 0 or +1 for finite numbers - that solves normalization of -0.0/+0.0
  • mantissa must be a positive odd integer or zero - that unifies all mantissas
  • exponent is also an integer, so the number is (* sign mantissa (expt 2 exp))
  • to hash unique values (like infinities) we will abuse sign to fit extra values

Every integer is a dyadic rational, so our task is to normalize it so that the mantissa is an odd number and adjust the exponent accordingly.

(defun compute-integer-dyad (number &optional (exp 0))
  (when (zerop number)
    (return-from compute-integer-dyad
      (values 0 0 0)))
  ;; In the real code use COUNT-TRAILING-ZEROS + ASH.
  ;; Loop division is to make the mechanism clear.
  (do ((sign (signum number))
       (mantissa (abs number) (ash mantissa -1))
       (exponent exp (1+ exponent)))
      ((oddp mantissa)
       (values sign mantissa exponent))))

The implementation for float is also straightforward thanks to the function INTEGER-DECODE-FLOAT. We also need to normalize the signed zero:

(defun compute-float-dyad (number)
  (cond ((nan-p number)
         (return-from compute-float-dyad
           (values -2 0 0)))
        ((negative-infinity-p number)
         (return-from compute-float-dyad
           (values -3 0 0)))
        ((positive-infinity-p number)
         (return-from compute-float-dyad
           (values +3 0 0))))
  (multiple-value-bind (mantissa exponent sign)
      (integer-decode-float number)
    (compute-integer-dyad (* sign mantissa) exponent)))

For ratios we will reuse the function that we have not defined in the last section to decide whether the ratio is dyadic and if it is - convert it to the canonical form:

(defun dyadic-ratio-p (number)
  ;; A positive integer is a power of 2 only when exactly one bit is set.
  (= 1 (logcount (denominator number))))

(defun compute-ratio-dyad (number)
  (values (signum number)
          ;; Ratios are already normalized(!)
          (abs (numerator number))
          ;; den = 2^k, shift = k+1 -> exponent = -k
          (- (1- (integer-length (denominator number))))))

Mind that the functions above are deliberately simple to illustrate how they should work. We have also used non-standard functions NAN-P and INFINITY-P that depend on the implementations extensions (or internals).

This is the most satisfying moment in the post - we have found an elegant and universal (in this domain) abstraction that avoids float-to-bignum conversion, hashes unequal numbers differently, and is easy to understand. That's the high point of this post and the reason I've dubbed it "heavenly delights". Alas, it is time to come back to earth and improve its performance. That's where the engineering lives.

3.1. Back to earth

We have an elegant conceptual model. The thing with elegant conceptual models is that they need to be dirtied to make them fast. And that's what we are going to do now: we will bastardize the clean abstraction and make it performant under usual scenarios without sacrificing precision. We are now optimizing.

Simplifications that we can climb down to from our normalized representation [sign, mantissa, exponent] model:

  1. When mantissa or exponent exceeds LONG-FLOAT precision, don't normalize the number

    As noted earlier, aside from floats, numbers in Common Lisp are disjoint, for example, there are no integers and ratios that are EQUALP to each other. In that case we use the most convenient hashing scheme for the specified type.

  2. Dyads representable as fixnums are hashed as a fixnum (a signed integer)

    This is an opportunistic optimization tailored for quick fixnum hashing. We already know how to correctly determine when a float can be reliably cast to fixnum and other numbers don't intersect with fixnums.

  3. Dyadic ratios in range are cast to long double and hashed as LONG-FLOAT

    This way we ensure that ratios and floats that are #'= are hashed the same. This is similar to "Round one" approach, but we retain the maximal precision.

  4. Integer floats and bignums in range are hashed in a dyadic form

    This step allows us to avoid coercing floats to bignums and is a big memory allocation save. A small cost for bignums is that we need to decide before hashing whether it is in the LONG-FLOAT precision range.

  5. Long floats exceeding double float precision are hashed in a dyadic form

    By avoiding lossy casts to double, we reduce number of collisions. Most notably, very small and very big values are not collapsed to zero and infinity. Such floats are hashed in a dyadic form because x87 floats have additional padding bits that may differ between equal values, so we can't hash memory.

Another minor optimization: we fold the sign and the exponent into a single word to have fewer hash state updates as 8*exponent+sign (sign has maximum 2 bits).

Notice that this scheme is very similar to the "Round one" approach. In practice it only differs in how we treat floats, bignums and ratios:

object round 1 current variant note
integer float fixnum or bignum fixnum or tuple depends on range
fractional float dfloat dfloat or lfloat depends on precision
dyadic-ratio dfloat dfloat or lfloat depends on precision
fixnum fixnum fixnum no change
bignum bignum bignum or tuple depends on precision

A few concrete examples should illustrate these simplifications. They do not try to test precise limits and the set is not exhaustive.

I'm assuming that FIXNUM has 62 bits and LONG-FLOAT has 64-bit mantissa, 15-bit exponent and 1-bit for sign – typical on x86 with GCC.

## dyadic number canonical representation cast note
0. (/ 1 (expt 2 (expt 2 15))) (1 1 -32768) ratio too small
1. (/ 1 (expt 2 (expt 2 11))) (1 1 -2048) lfloat  
2. 3/8 (1 3 -3) dfloat  
3. 42 (1 21 1) fixnum  
4. most-positive-fixnum (1 most-positive-fixnum 0) fixnum  
5. most-negative-fixnum (-1 1 61) fixnum  
6. (1+ most-positive-fixnum) (1 1 61) dyadic  
7. (1- most-negative-fixnum) (-1 2305843009213693953 0) dyadic  
8. (expt 2 32768) (1 1 32768) bignum  
9. (/ (1+ (expt 2 40)) 2) (1 (1+ (expt 2 40)) -1) dfloat  
a. (/ (1+ (expt 2 53)) 2) (1 (1+ (expt 2 53)) -1) lfloat  
b. (/ (1+ (expt 2 64)) 2) (1 (1+ (expt 2 64)) -1) ratio too big
c. 13.0 (1 13 0) fixnum  
d. (expt 2.0 61) (1 1 61) dyadic  
e. (expt 2.0l0 16383) (1 1 16383) dyadic  
f. (expt 2.0l0 16384) (3 0 0) dfloat infinity
case 0
the number underflows long-float exponent precision
case 1
the number is representable as LONG-FLOAT but not as DOUBLE-FLOAT
case a
the number is representable as LONG-FLOAT but not as DOUBLE-FLOAT
case b
the number overflows LONG-FLOAT mantissa precision
case e
the number narrowly fits in LONG-FLOAT
case f
the number overflows LONG-FLOAT (infinity) – may signal a condition

Illustrative pseudocode:

;;; There is something to be said about conventions. Our dyadic representation
;;; treats the mantissa as an odd integer, but the C representation of floats
;;; treats the mantissa as a fraction [0.5, 1.0). In practice this means that
;;; exponents in our canonical representation must be recalculated, because:
;;;
;;;   our-mantissa === (shift-to-odd (ash float-mantissa +ldbl-mant-dig+))
;;;   our-min-exp  === (- +ldbl-min-exp+ +ldbl-mant-dig+)
;;;   our-max-exp  === (- +ldbl-max-exp+ (integer-length our-mantissa))
;;;
;;; Note that FLOAT-MANTISSA assumes a fraction, but in practice we can usually
;;; extract bits directly and skip the shift by interpreting it as significand.
(defun hash-dyadic-number (state number)
  (multiple-value-bind (sign mantissa exponent)
      (dyadic-representation number)
    (let* ((num-len (integer-length mantissa))
           (min-exp (- +ldbl-min-exp+ +ldbl-mant-dig+))
           (max-exp (- +ldbl-max-exp+ num-len)))
      (if (and (<= num-len +ldbl-mant-dig+)
               (<= min-exp exponent max-exp))
          (hash-dyad state sign mantissa exponent)
          (hash-type state number)))))

3.2. Gravel details

Without further ado, let's dig into the actual implementation. I'm going to show only relevant parts of C code for brevity. If you are not interested in C code and microoptimizations, then just skip this section and move to benchmarks. Here is a TL;DR table (complexes are normalized and each part is hashed with a tag):

type hash as why?
fixnum fixnum performance
bignum bignum / dyadic performance / equivalence (lfloat/dfloat)
ratio ratio / lfloat performance / equivalence (lfloat/dfloat)
dfloat fixnum / dyadic / dfloat performance / equivalence / performance
lfloat dfloat / fixnum / dyadic performance / performance / correctness

In two places we will hash integers that may be either fixnums or bignums:

  • the mantissa in a dyadic form (long double mantissa is 64bit on x86-64)
  • a ratio's numerator and denominator when the ratio is not a dyadic number

Hashing them is straightforward. Note that hashing the fixnum is always cheap - we hash a single word.

static inline void
hash_fixnum_data(cl_hashstate *h, cl_object x) {
  hash_word(h, ecl_fixnum(x));
}

#define hash_fixnum(h,x) hash_fixnum_data(h,x)

static inline void
hash_bignum_data(cl_hashstate *h, cl_object x) {
  hash_word(h, ecl_bigsgn(x));
  hash_data(h,
            ECL_BIGNUM_LIMBS(x),
            ECL_BIGNUM_USIZE(x) * sizeof(ecl_limb_t));
}

static void
hash_integer(cl_hashstate *h, cl_object x)
{
  if (ECL_FIXNUMP(x)) {
    hash_fixnum_data(h, x);
  } else {
    hash_bignum_data(h, x);
  }
}

Previously we were concerned with consing. This is why we go an extra mile to not allocate bignums unnecessarily when we hash a bignum in a dyadic form. We operate on a scratch register that is a thread-local variable in ECL when we extract a mantissa:

static inline void
hash_and_free_bignum_register(cl_hashstate *h, cl_object mantissa) {
  /* INV this function assumes that mantissa is already positive. The bignum may
     not be normalized to fixnum. We free the register after hashing. */
  if (ECL_BIGNUM_SIZE(mantissa) == 1) {
    ecl_limb_t y = ECL_BIGNUM_LIMBS(mantissa)[0];
    if (y <= MOST_POSITIVE_FIXNUM) {
      hash_word(h, y);
      goto DONE;
    }
  }
  hash_bignum_data(h, mantissa);
 DONE:
  _ecl_big_register_free(mantissa);
}

/* When hashing bignums we see whether they fit in LONG-FLOAT and only then we
   cast it to a dyadic form. Otherwise we directly hash limbs. */
static void
hash_bignum(cl_hashstate *h, cl_object x) {
  cl_fixnum length = _ecl_big_integer_length(x);
  cl_fixnum exponent = _ecl_big_ctz(x);
  if (length-exponent<=LDBL_MANT_DIG && length<=LDBL_MAX_EXP) {
    /* To avoid allocating fresh bignums by ABS and ASH we opencode this:
       cl_object mantissa = ecl_ash(ecl_abs(x), -exponent); */
    cl_object reg = _ecl_big_register2();
    cl_fixnum signum = ecl_bigsgn(x);
    if (signum<0) {
      _ecl_big_neg(reg, x);
      _ecl_big_div_2exp(reg, reg, exponent);
    }
    else {
      _ecl_big_div_2exp(reg, x, exponent);
    }
    hash_word(h, 8*exponent+signum);
    hash_and_free_bignum_register(h, reg);
  } else {
    hash_bignum_data(h, x);
  }
}

Hashing a ratio is also plain. When the ratio is dyadic and its precision does not exceed long double then we coerce it to that type and hash it. Otherwise we add the tag and hash both integers. We are careful to not allocate memory.

static void
hash_ratio(cl_hashstate *h, cl_object x) {
  /* When the ratio is dyadic and within long-float precision, then we cast it
     to long double for consistent hashes. Otherwise we hash ratio as is. */
  cl_object num = ecl_ratio_num(x);
  cl_object den = ecl_ratio_den(x);
  /* Ratio is dyadic when denominator is a power of two. To avoid bignum
     arithmetic we provide an optimized path for each subtype of integer.
     ecl_zerop(ecl_boole(ECL_BOOLAND, den, ecl_one_minus(den))); */
  bool dyadic_p;
  if (ECL_FIXNUMP(den)) {
    /* Denominator is always positive, so fixnump(x) -> fixnump(x-1) */
    cl_fixnum dfix = ecl_fixnum(den);
    dyadic_p = !(dfix & (dfix-1));
  } else {
    /* When bignum is a pow2, then integer_length == ctz+1 or (popcount==1) */
    dyadic_p = ((_ecl_big_ctz(den)+1) == _ecl_big_integer_length(den));
  }
  if (dyadic_p) {
    /* Normally we would call here
       cl_fixnum length = ecl_integer_length(ecl_abs(num));

       But! Numerator is normalized to an odd integer because denominator is a
       power of two. INTEGER-LENGTH returns different values for X and -X only
       when X is a power of two, and the only odd power of two is X=1.

       (INTEGER-LENGTH -1) == 0 and 0 <= LDBL_MANT_DIG
       (INTEGER-LENGTH +1) == 1 and 1 <= LDBL_MANT_DIG

       This is why we don't need to call ABS on the numerator. QED. */
    cl_fixnum length = (ECL_FIXNUMP(num)
                        ? ecl_integer_length(num)
                        : _ecl_big_integer_length(num));
    cl_fixnum exponent = -(ecl_integer_length(den)-1);
    if (length <= LDBL_MANT_DIG && exponent >= LDBL_MIN_EXP-LDBL_MANT_DIG) {
      /* Generic way to do this is: hash_long_float(h, ecl_to_long_double(x));
         that path recomputes mantissa and exponent from ratio using a generic
         arithmetic. We already have everything ready. */
      long double value = (ECL_FIXNUMP(num)
                           ? ecl_fixnum(num)
                           : _ecl_big_get_lf(num));
      value = ldexpl(value, exponent);
      hash_long_float(h, value);
      return;
    }
  }
  /* Fall-through. */
  hash_word(h, t_ratio);
  hash_integer(h, num);
  hash_integer(h, den);
}

Hashing floats is the most demanding part in this program:

  1. DOUBLE-FLOAT: the first branch ensures the same hashes for fixnums, bignums, and integer float types, while the second branch ensures the same hashes for ratios and fractional float types.
  2. LONG-FLOAT: the first branch checks whether we can cast to double without losing precision. The second branch ensures same hashes for fixnums. The third branch unconditionally hashes the value in a dyadic form.

Initially I've introduced functions decode_lf and decode_df that extracted mantissa and exponent from the number, but benchmarks showed that these small allocations dominate both time and consing for relevant profiles. This is why I've fused decoding and hashing and operate on a preallocated register. That's the difference between coming up first and coming up third on the benchmark.

Decoding and hashing double and long double in a dyadic form are practically the same, so I'm going to show only hash_lfloat version. Both functions have a fast path when the mantissa fits in cl_index, and a portable slow path when it doesn't. Initially I've picked unsigned long long, but this type can't be directly assigned to a bignum in GMP, so I've decided on a more robust type.

Functions hash_dfloat and hash_lfloat are identical except for DBL_MANT_DIG -> LDBL_MANT_DIG, ldexp -> ldexpl and frexp -> frexpl. Common Lisp, with its organic macros, could save us repetition and expand a single macro twice, but C preprocessor macros get hairy fast, so it is better to copy-paste the code:

/* INV value is guaranteed to be finite and != 0. */

#define DECODE_SIGNUM(value,signum) \
  do { if (signbit(value)) { signum=-1; value=-value; } } while(0)

/* ... hash_dfloat(cl_hashstate *h, double value) ... */

static inline void
hash_lfloat(cl_hashstate *h, long double value)
{
#if LDBL_MANT_DIG <= ECL_FIXNUM_BITS
  int ctz, exponent, signum=1;
  cl_index mantissa;
  DECODE_SIGNUM(value, signum);
  value = ldexpl(frexpl(value, &exponent), LDBL_MANT_DIG);
  exponent -= LDBL_MANT_DIG;
  mantissa = (cl_index)value;
  ctz = ecl_ctz(mantissa);
  exponent += ctz;
  mantissa >>= ctz;
  /* binary80 mantissa is 64 bits so it can falsify <= MOST_POSITIVE_FIXNUM. */
  if (mantissa <= MOST_POSITIVE_FIXNUM) {
    hash_word(h, 8*exponent+signum);
    hash_word(h, mantissa);
  } else {
    cl_object reg = _ecl_big_register2();
    _ecl_big_set_idx(reg, mantissa);
    hash_word(h, 8*exponent+signum);
    hash_bignum_data(h, reg);
    _ecl_big_register_free(reg);
  }
#else /* Happens for 128bit floats (i.e aarch64). */
  const int fixnum_bits = ECL_FIXNUM_BITS-ECL_TAG_BITS-1;
  int ctz=0, exponent, signum=1;
  cl_object mantissa = _ecl_big_register2();
  cl_fixnum helper, iterator;
  DECODE_SIGNUM(value, signum);
  value = frexpl(value, &exponent);
  _ecl_big_set_ui(mantissa, 0);
  for(iterator=0; iterator<LDBL_MANT_DIG && value; iterator+=fixnum_bits) {
    value = ldexpl(value, fixnum_bits);
    helper = (cl_fixnum)value;
    value -= helper;
    _ecl_big_mul_2exp(mantissa, mantissa, fixnum_bits);
    _ecl_big_add_ui(mantissa, mantissa, helper);
    /* When this chunk contains only 0s, then we extend trailing zeros by
       fixnum_bits (chunk's size). Otherwise we start counting again. */
    ctz = !helper ? ctz+fixnum_bits : ecl_ctz(helper);
  }
  /* ctz is a trailing 0 count for the whole mantissa. iterator denotes how many
     bits we have shifted the mantissa. */
  exponent += ctz - iterator;
  _ecl_big_div_2exp(mantissa, mantissa, ctz);
  hash_word(h, 8*exponent+signum);
  hash_and_free_bignum_register(h, mantissa);
#endif
}
#undef DECODE_SIGNUM

At last we can hash some floats. Hashing single floats is trivial (we cast them to double float) while hashing a long float requires more work:

integer path
we need to extract the mantissa from it separately because it can store bignums outside of a double float range.
fraction path
DOUBLE-FLOAT is hashed as is, LONG-FLOAT are hashed as a dyad unless it can be represented as DOUBLE-FLOAT, in that case it is cast to it
#define hash_single_float(h,v) hash_double_float((h),(double)(v))

static void
hash_double_float(cl_hashstate *h, double value) {
  if (isfinite(value) && (value==trunc(value))) {
    const double limit = ldexp(1.0, ECL_FIXNUM_BITS-ECL_TAG_BITS-1);
    if (value < limit && value >= -limit) {
      hash_word(h, (cl_fixnum)value);
      return;
    }
    hash_dfloat(h, value);
    return;
  }
  /* Fall-through. */
  hash_data(h, &value, sizeof(value));
}

/* We need to ensure, that when long double can be represented as double without
   loss of precision, that is value == (double)value, to hash it as double. */
static void
hash_long_float(cl_hashstate *h, long double value) {
  /* Hash as double. */
  if (!isfinite(value)
      || (fabsl(value) <= DBL_MAX && value==(double)value) ) {
    hash_double_float(h, (double)value);
    return;
  }
  /* Hash as fixnum. */
  {
    const long double limit = ldexpl(1.0L, ECL_FIXNUM_BITS-ECL_TAG_BITS-1);
    if ((value==truncl(value)) && (value < limit) && value >= -limit) {
      hash_word(h, (cl_fixnum)value);
      return;
    }
  }
  /* Hash as long double in dyadic form -- this is both for compatibility with
     bignums and to avoid hashing padding bits on x87. */
  hash_lfloat(h, value);
}

And.. that's all. Complex numbers are hashed the same - when the complex float imaginary part is zero then we hash only the real part, otherwise we hash both parts. Summing things up, here are the dominant costs of the procedure:

type decision cost dyadic hash cost normal hash cost
fixnum (none) same as for EQL same as for EQL
bignum (negligible) (ash (abs x) -exp) same as for EQL
ratio (negligible) hash_long_float same as for EQL
float (negligible) hash_{dfloat,lfloat} same as for EQL
  • bignum decision cost boils down to counting trailing zeros, the dyadic hash operates in a register and it doesn't cons
  • ratio decision cost is optimized to not perform bignum arithmetic, so the decision cost is negligible and the main cost is in hashing long double
  • float creates an integer from the mantissa - in most cases it is a fixnum, otherwise it operates on a bignum register and it doesn't cons either

This section might not have been the most pleasant read (a lot of C code), but I hope that it gave you some insight into how optimizing ECL hot paths looks like. Certainly it would be nice to have Common Lisp compiler that targets C! Oh…

4. Benchmarks - knockout

I initially planned to run ad hoc benchmarks and get over with it, but I had too much fun writing up tests and coming up with interesting benchmark profiles and fell into another rabbit hole. In this section we'll compare ECL with itself (of course), but we will also discuss other implementations.

First let's focus on tests. I've devised a few profiles for comparisons:

:AVERAGE
we pick randomly rational and float numbers
:TYPICAL
fixnums, fixnum uuids, small floats and bignums in form 2n
:DYADIC
rational and float numbers with overlapping values being =
:COLLIDE
white-box test that exploits casting LONG-FLOAT to DOUBLE-FLOAT
:BEYOND
white-box test that tests dyadic rationals beyond LONG-FLOAT range
:FIXNUM :BIGNUM :RATIO :DOUBLE
basic type-specific benchmark

All benchmarks first generate 216 keys according to their profile and prefill the hash table in the setup phase to avoid resizing. Only after that we run the benchmark. Each profile has the same number of keys that are randomized during setup. Each test is run 8 times to average results.

We measure both run time and consed bytes. The benchmark itself runs SETHASH and GETHASH for each key in the collection, so the hash table implementation impacts cross-implementation comparisons. On the bright side, it also reveals when there are systematic collisions between hashes.

Here is an interesting story (relevant to these charts!). While analyzing data I've noticed that "ECL-round2" unexpectedly conses for three profiles: :DYADIC, :TYPICAL and :AVERAGE. I've felt very disappointed with these, because I went to great lengths to avoid consing. The investigation revealed that if we don't mix in these tests floats and rationals then consing is consistently zero. That was the "aha!" moment - hash table allocates memory when it compares float and rational keys! I'm keeping the figures as-is, but keep in mind that "ECL-round2" hashing really doesn't cons; allocations come from the key comparison. I could pull out my yak shaver and fix EQUALP too, but this descent stops being funny.

ECL variants are: "warmup", "round one" and "round two" that correspond to approaches discussed earlier: cast everything to double, type-specific hashes, and the final version where we exploit a dyadic canonical form. All tests are performed using the new hash function (xxhash) and hash table (swiss).

Tested implementations are CCL, ECL, LispWorks and SBCL. There are caveats:

  • I initially planned to include ABCL and CLASP too, but a smoke test revealed ABCL#763 and CLASP#1876. Both share the same flaw as ECL before changes described in this post, that is they don't hash numbers correctly under EQUALP. Benchmarking them would be beside the point.
  • LispWorks performs badly on profiles any float numbers and other results are dwarfed by it, so I've excluded LW from some plots (but accounted for it in relevant analysis)
  • CCL is the mirror image of LispWorks, and performs badly on profiles with rationals (and it is great with floats), so it is also skipped on some plots
  • The :COLLIDE test does not apply to other implementations because they don't have LONG-FLOAT that is separate from DOUBLE-FLOAT - we use :TYPICAL instead

The smoke test:

(defvar *ht* (make-hash-table :test #'equalp))
(setf (gethash 1/4 *ht*) 42)
(unless (eql (gethash 0.25 *ht*) 42) ; a proper test should cover more pairs
  (format t "ERROR: 1/4 and 0.25 do not share the hash value under EQUALP.~%"))

All charts report either elapsed time or allocated memory aggregated for the whole execution. Smaller is better. Test results are normalized to [0, 1] relative to the slowest / most consing variant in each panel. "0.00" means "below 0.005" of the maximum, not zero. All measurements were performed on X86-64 Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz.

One of the hardest parts in analyzing data is to decide what we can remove without simplifying the picture too much. Interpretations presented in this section skip many benchmarks to present an understandable story.

If you are curious whether new ECL excels at complex floats (it does), or whether it is true that small doubles and fixnums do not cons (they don't), then you can dive straight into the raw data or, if you don't trust my numbers, then you may inspect the of the number generator.

4.1. ECL vs ECL

First we will compare ECL variants developed in this post. The first chart shows a benchmark for basic types:

equalp-ecl-basic-types.png

Figure 6: (ECL-warmup ECL-round1 ECL-round2) x BASIC-TYPES x (TIME CONS).

A few interesting observations emerge from this chart:

  1. Hashing doubles is fastest on "ECL-warmup", because this implementation is simplest for that particular profile. It also doesn't cons. "ECL-round1" is dominated by memory allocations for large double values that are bignums.
  2. Hashing ratios has progressively better results with each round, both the time and consing.
  3. Hashing bignums is a mirror image to hashing doubles, where "ECL-round1" excels at bignums, "ECL-warmup" must coerce bignums to doubles and memory allocation dominates its time. "ECL-round2" is as performant as "ECL-round1".
  4. Fixnums on all variants are on a relatively fast path and don't need to cons at all.

Notice that "ECL-round2" is slower only when we hash specifically doubles. Otherwise it is always tied or it is the fastest. It also doesn't cons.

It already looks good, but charts start to look even more interesting when we start exploiting mixed data patterns:

equalp-ecl-mixed-data.png

Figure 7: (ECL-warmup ECL-round1 ECL-round2) x MIXED-DATA x (TIME CONS).

  1. The "beyond" profile is a benchmark where we generate bignums and ratios that can't be represented as float, but have a shape that resembles floats - both have a mantissa that can be stored in a double and an exponent that doesn't fit in binary128 floats (the most precise float on ECL aarch64 and no tested Lisp has a wider float).

    And it shows. "ECL-warmup" takes the bait and collapses everything to double. That spikes both allocations and collisions. "ECL-round1" avoids part of that cost because bignums are hashed as is and they avoid collapsing to a single hash (double positive infinity). "ECL-round2" avoids both allocation and the collision traps and it is 400x faster (0.3s vs 125s) and doesn't cons while "ECL-warmup" conses 2GB.

  2. The "collide" profile is similar, but numbers can be neatly represented as a long float (binary80) and not as a double float (binary64). That means in particular that both ratios and bignums must be hashed in a compatible manner to floats. Once again "ECL-round2" is very fast (600x faster! 0.2s vs 118s) and doesn't cons, while "ECL-warmup" conses 833MB. "ECL-round2" has much less collisions than "ECL-warmup" thanks to exact bignum hashing.
  3. The "dyadic" profile mixes fixnums, double floats, bignums in double float range and dyadic ratios in double float range. This profile forces the need to bring all numbers to the same canonical representation and does not exhibit any systematic collisions. Since all here boils down to doubles, "ECL-warmup" conses less than "ECL-round1", yet "ECL-round2" is even better thanks to our optimizations. Little consing that is exhibited comes from comparing floats and bignums with EQUALP (not from hashing).
  4. The "average" profile takes rational and float numbers at random. Here we can again see that "ECL-round1" was not a regression over "ECL-warmup" - it was a targeted optimization that tried to balance effort between different types of numbers. Still, "ECL-round2" wins clearly against both variants.

My takeaways here are that:

  • specialized implementations are better for their particular data profile, notably "ECL-warmup" excels at doubles; "ECL-round1" ties "ECL-round2" at bignums and balances other types well
  • "ECL-round1" approach optimizes for typical cases, but it is not very frugal with memory (to the point where allocations dominate the benchmark in doubles)
  • "ECL-round2" also optimizes for typical cases but it is also austere with memory allocations and avoids hash collisions - that is responsible for two orders of magnitude faster and leaner implementation for adverse profiles

4.2. ECL vs the world

Comparing implementations between each other is inherently noisy. They don't share the same hash table implementation and various unrelated operations on the hashing and hash table path have different cost profiles. That said with a big set of data we can clearly see some trends. Let's start with basic types:

equalp-all-basic-types.png

Figure 8: (CCL ECL LispWorks SBCL) x BASIC-TYPES x (TIME CONS).

LispWorks is excluded from the test involving floats because it is around 2500x slower than CCL (96s vs 0.04s) and conses 66MB while other implementations don't cons at all. In benchmarks involving rational numbers it is competitive. My guess is that LispWorks calls RATIONALIZE on floats and that get costly fast.

CCL is another side of the same coin. It performs well for floats (around 1.7x slower than ECL and SBCL), but it is much worse for rationals. The difference is not that drastic but still much slower for bignums compared to LispWorks (0.18s vs 0.03s). It is surprising but it allocates data even for FIXNUMs. It probably calls FLOAT on all numbers before hashing.

SBCL heavily optimizes fixnums, bignums, and doubles - it is a leader on these basic types and it doesn't cons. It drops a ball with ratios where it is slower and conses 155MB (while ECL nor LispWorks don't allocate memory for ratios).

ECL never conses and wins for ratios, while for other basic types it is always second. For BIGNUM SBCL pulls ahead, while for FIXNUM and DOUBLE it follows closely.

equalp-all-mixed-data.png

Figure 9: (CCL ECL LispWorks SBCL) x MIXED-DATA x (TIME CONS).

Results in these benchmarks are implicit from tests on basic types:

  • BEYOND, DYADIC and AVERAGE involve floats, so LispWorks is too slow to include. SBCL is also underperforming on these tests, because these profiles contain ratios - the cost seems to be dominated by memory allocations.
  • TYPICAL profile is manageable for all implementations, but both CCL and LispWorks underperform because both (small) floats and rationals are in the test set. CCL allocates much more memory than others. SBCL performs well, but is slower than ECL.
  • In all these tests with mixed numbers ECL is the leader and allocates least (as noted earlier, hashing itself doesn't cons at all).

My takeaway is that each implementation could close the gap to the others if:

  • LispWorks adds hashing specialization for floats
  • CCL adds hashing specialization for rationals
  • SBCL adds hashing specialization for ratios

This new approach of ECL is competitive with all implementations on each metric and it is either the first or a close second with the biggest (around 1.5x) gap to SBCL hashing bignums.

5. Summary

The main takeaway here is that every dyadic rational has one canonical form that may be used to produce good hashes under the EQUALP predicate and that efficient implementations take liberties with simplifications after absorbing the model.

It may look like we have abandoned the elegant dyadic model in the later phase, but that's not true: we don't lose precision by lossy casting to double and all numbers except equal ones are hashed differently (hashing differently does not imply different hashes just like tossing a dice differently does not guarantee different results).

Another interesting insight is that we can learn a lot about strategies used by different implementations by merely benchmarking them with cleverly put number selection profiles.

In practice EQUALP is not often used as a hash test, so while the numbers look impressive, the new approach is not a game changer. That said, there is value in hashing under EQUALP precisely because it coalesces different numbers. Usage may follow when implementations are performant, while underperforming abstractions will almost certainly be skipped.

That's about the hashing itself, but the post is not only about hashing. Note how we have started with a simple baseline model, improved it and then refined our understanding with an elegant conceptual model. We didn't stop there: we turned it into an efficient implementation through the optimization and validation loop. That's an engineering lesson worth remembering even if you don't care much about heavenly delights of hashing numbers under EQUALP.

Uff, the summary was exhausting. For me, this was certainly a fun trip. I've recently learned a lot about hashing, hash tables, number equivalence, micro-optimizations, benchmarking and diving too deep. Look forward to:

  • a blogpost that discusses new hash table and generic function implementations
  • the next release with all accumulated performance and conformance improvements

You may find the current progress in the ECL repository under branches xxhash, swiss-ht and improve-gf-cache.

Happy Hackshing!

Daniel

PS If you liked this post or have some interesting insights, then let's chat.

PPS If you'd like to see more rabbit hole investigations like this one, you can support me on Patreon.

PPPS I'd like to thank Charlie McMackin for proofreading this text and providing many valuable remarks.

Marco Antoniotti — Exercising on a Threadmi&lambda;, multitasking

· 35 days ago

As I get older, I need to exercise. I decided to use a Threadmiλ.

Of course, this is another rabbit's hole I fell into many years ago and I am getting out of it right now. The reason I fell into this specific rabbit's hole is the lack of portable timeout facilities in the testing frameworks out there, including my favorite one, FiveAM. More on this later.

My solution, NIH-syndrome-inspired of course, was to write a portability layer for timeout facilities.

Which begged the question: why not Bordeaux Threads?

The answer is, again, NIH and the fact that Bordeaux Threads has undergone some bit rot over the years and that it is not fully complete with respect to many of the implementations out there, especially when it comes to the facilities that the implementations provide.

The result is Threadmiλ (or threadmiλ, or ThreadMIL, or threadmilambda...), i.e., a Bordeaux Threads like library, re-done in MILan; the λ is de rigueur.

Threadmiλ

As I said, Threadmiλ (Threadmil) is a fork and a somewhat re-implementation of the well known Bordeaux Threads library that aims to make it even more CL-centric, expand it and fix the semantics of a few constructs, most notably the timeout machinery.

Threadmiλ implements, leveraging the underlying CL, the following threading facilities.

  • Threads
  • Locks
  • Semaphores
  • Condition Variables
  • Timers
  • Mailboxes
  • Barriers
  • Atomics
  • Timeouts

These are the facilities available in most CL, especially Lispworks.

Current Implementation Status

The table below gives you a quick status of the support for a number of implementations. T means that all the tests for the specific feature pass, NIL means they do not, and and empty cell means they have not been tried yet (or at all). A rational number tells you how many test pass with respect to how many fail or are skipped. The test suite uses fiveam.

LW SBCL CMUCL ECL ABCL CCL CLISP ACL
Threads T T T T T T
Locks (1) T 14/17 T T 15/21 14/18
Semaphores T T T T T T
Condition Vars T T T T T T
Timeouts (2) T T T T T T
Timers T T T T T T
Mailboxes T T T T T T
Barriers T T 11/12 T T T
Atomics T T T T T T

Note that the table simply reflects the current compliance with the set of tests. Adding some tests may change the entries in the table. As you can see CMUCL and CLISP are not supported, and neither are several other implementations purportedly supported by Bordeaux Threads.
(1) Apparently, SBCL, CCL and ACL do not have full a recursive locks API; it seems all locks are such. The missing bits are different and this is reflected in the number of tests actually performed. In the future the regular API may be used and the missing tests will just work.
(2) The timeout tests for ABCL sometime fail unexpectedly; this is probably due to the fact that sleep is quite finicky both at the CL and the Java level. Tracking down why is left as an exercise for the ABCL developers (not the only one they have been assigned: hint, hint).

Where You Can Get your Threadmiλ

The main documentation page can be found https://threadmil.common-lisp.dev.
/ The project page is at https://gitlab.common-lisp.net/mantoniotti/threadmilambda

How Did I Get Here?

Before AI stuff I used some testing frameworks to tortur... pardon, evaluate students' projects (yes, I inflict CL on them). Oftentimes, some project would loop and the testing framework would just sit there. A check of most CL testing framworks showed (I may be wrong) that they lacked a proper timout machinery (some declare it, but deep down it is fake).

I thus set out to create a portable with-timeout macro. That was the mistake that led to Threadmiλ.

Now, testing frameworks developers have no more excuses.

Disclaimer

As usual here you have the scariest disclaimer here. The library is bound to have bugs and race conditions.

AI was used only to generate a few of the tests.

Any Help Appreciated

Of course you are free to fork the project subject to the current licensing scheme. However, before you do so, I ask you to consider plain old "cooperation" by asking me to become a developer. It helps keeping the entropy level at an acceptable level.

Of course, in this case, I did not heed my own advice, and yet...


'(cheers)

Marco Antoniotti 2026-10-24

Joe Marshall — lisp.md: System Instructions for Lisp

· 71 days ago

I have an extensive lisp.md file that I include in my system instructions when I am vibe coding Common Lisp. Feel free to use these suggestions or adapt them to your own style.

Common Lisp & Functional Programming Directives

1. Identity, Role & Operating Posture

  • Role: You are a highly capable, supportive, and exceptionally effective companion to your user ('the Boss'). Your primary goal is to assist, understand, and anticipate his needs, providing proactive and insightful support.
  • Mastery & Humility: You possess the expertise of a world-class functional programmer with absolute mastery in Common Lisp (macros, CLOS, conditions, metaprogramming, libraries, and idiomatic patterns). You are humble and recognize that the Boss is a superior programmer; however, never hesitate to point out when the Boss is making a mistake and offer alternative solutions.
  • Support-First Focus: Seamlessly integrate companionable support with deep technical competence. Focus primarily on support—do not force technical demonstrations or unprompted Common Lisp snippets into every interaction. Provide technical answers only when requested or needed.
  • Documentation: Prefer comprehensive documentation strings over inline comments across all functions, classes, and constructs. Overuse, rather than underuse, docstrings to provide complete standalone context.

2. Naming & Lexical Conventions

Adhere strictly to these semantic naming signals:

  • Low-Level / Unsafe (% Prefix): When writing low-level code that punctures abstractions or carries unexpected preconditions, prefix the symbol with % (following and strictly enforcing the Common Lisp standard library convention).
  • Side-Effects (! Suffix): When writing functions that operate primarily through mutation or side effects, suffix the function name with ! (Scheme convention).
  • Predicates (? Suffix): When writing boolean predicates, suffix the function name with ? (Scheme convention). Prefer the ? suffix over the p suffix (Common Lisp convention) for clarity and consistency.
  • Symmetrical Arguments: In binary functions with symmetrical arguments, name the parameters left and right unless domain-specific names are distinctly superior.
  • Argument Ordering (Noun-First & Variance Hierarchy): When defining function parameter lists, order arguments deliberately from primary subject to variable context:
    • The "Noun" First: The primary entity, target data structure, or receiver of the operation (the "noun") must occupy the leftmost argument position. Subsequent arguments must follow in descending order of importance, configuration, or specificity.
    • Dynamic Variance in Iteration: When designing functions intended for collection transformations or iterative loops, order arguments such that the rightmost argument changes fastest (highest variance), while leftmost arguments remain invariant (lowest variance). This guarantees natural compatibility with left-to-right partial application (curry, partial-apply-left) when passing functions into higher-order combinators.
  • String Literals for Package & Symbol Designators: When generating package forms (e.g., defpackage, in-package), consistently use literal strings rather than symbols ("MY-PACKAGE" and "MY-SYMBOL", uppercase per CL convention). For general non-symbol string designators, use literal lowercase strings (e.g., "my-string").

3. Data Structures & CLOS

Emphasize immutability and declarative object dispatch:

  • Immutability First: Always prefer immutable data structures and pure functions.
  • defstruct Standards:
    • Mark all slots as :read-only t unless explicitly intended to be mutable.
    • Always use the :conc-name argument formatted as the type name followed by a slash (type/). For example, slot bar in struct foo generates the accessor foo/bar.
  • defclass Standards:
    • Always prefer :reader methods over :accessor methods unless mutability is required.
    • Reader methods must be prefixed with get- rather than the class name. For example, slot bar in class foo uses reader get-bar.
  • Generic Dispatch over Branching:
    • Transform etypecase bodies into CLOS generic functions with methods specialized on the classes being dispatched.
    • Transform ecase bodies into generic functions with methods specialized on eql values.

4. Control Flow, Recursion & Scoping

Prioritize explicit, descriptive, and well-scoped functional constructs over unstructured jumps:

  • No Imperative Loops: Strictly avoid imperative loop constructs. Do not use the loop macro.
  • Named let for Recursion: For iterative or stateful processes that cannot be expressed via higher-order functions, use tail-recursive named let expressions.
    • Syntax: (let name ((var1 expr1) (var2 expr2)) ...body...)
    • Semantics: The symbolic name directly follows let and binds the enclosing lambda, enabling self-referential tail calls within the body.
    • Constraints: This is part of the standard let macro syntax here (not a separate named-let macro). Never use loop as the loop name (it won't work); use next where applicable.
  • Proper Tail Recursion (TCO) & Constant Stack Space: Assume the underlying Common Lisp implementation (such as SBCL) guarantees proper tail-call optimization (TCO). Tail-recursive calls—particularly within named let expressions—execute in constant $O(1)$ stack space without accumulating stack frames or risking stack overflow. Write tail-recursive algorithms with full confidence; when required to enforce or guarantee elimination across compiler policies, supply appropriate optimization declarations, such as (declare (optimize (speed 3) (safety 1) (debug 1))).
  • No Unstructured Control Flow: Avoid generic labels or unstructured control-flow mechanisms (tagbody/go). Keep bindings clear, defined, and tightly scoped.
  • Continuation-Passing Style (CPS): Employ CPS when it is the most natural paradigm for the problem. When using CPS, always pass the continuation function as the final argument, invoking it with the computed result upon completion.
  • Local Boilerplate (macrolet): When generating repetitive boilerplate that does not escape the file, encapsulate it cleanly within a macrolet.
  • Macro Hygiene & Single Evaluation: When writing macros that take expressions as arguments, always use alexandria:with-gensyms to prevent variable capture and alexandria:once-only to guarantee arguments are evaluated exactly once and in left-to-right order.
  • Expressive Destructuring: Avoid deep accessor chains like car, cadr, or cddr. Favor destructuring-bind or multiple-value-bind to unpack compound structures into clearly named bindings at the entry of the computation.
  • Structured Conditions: When defining domain failure modes or invariant violations, prefer signaling typed conditions via define-condition and cerror / signal over generic raw-string (error "...") calls. This preserves restartability and structured inspection.
  • Native Multiple Values over Consing: When a function computes multiple related results, always use Common Lisp's native values mechanism rather than consing intermediate lists or ad-hoc tuples. Callers should capture them cleanly via multiple-value-bind or nth-value.
  • Defensive Type Checking: Favor check-type at public function boundaries for defensive parameter verification, keeping invariant checks concise and declarative.

5. Collection Transformations & Higher-Order Functions

Transform collections purely using higher-order combinators and pre-defined functional libraries:

  • Pre-Loaded Libraries: Alexandria, FUNCTION, and the fold-left primitive are pre-defined and ready for use. Do not emit their implementations.
  • Aggregation via fold-left: Always choose fold-left over the general reduce function when collapsing a collection to an accumulated value, ensuring explicit left-associative reduction.
  • Selection via remove (Inverted Logic): Instead of a standard filter function, use remove paired with the negation of the selection predicate (e.g., using the :test-not keyword argument) to retain matching elements.
  • Partial Application: Utilize Alexandria's curry and rcurry, or FUNCTION's partial-apply-left and partial-apply-right for clean, point-free partial function application.
  • Higher-Order Callback Signatures (The Echo Principle): When designing higher-order functions that accept a callable (combiner, transformer, predicate, or reducer) alongside domain arguments (collections, accumulators, seeds, or context), the parameters accepted by the callback must be an **exact positional echo** of the corresponding arguments in the enclosing higher-order signature:
    • Relative Positional Invariant:The relative left-to-right order of domain arguments in the outer call dictates the parameter order passed into the inner callable.
    • Exemplar — fold-left vs. fold-right:
      • In (fold-left function initial list &rest lists), the seed accumulator (initial) appears to the left of the sequences. Therefore, the folding function must accept arguments ordered as (state item1 ... itemN): the accumulated state on the left, followed by the sequence elements.
      • In fold-right, the signature is semantically n-ary with the base accumulator at the terminal position: (fold-right function list1 ... listN final) (where &rest args is an implementation detail to capture the trailing final). Therefore, the folding function must accept arguments ordered as (item1 ... itemN state): the sequence elements from left to right, followed by the accumulated state at the far right.
    • Self-Documenting Invariant: The outer call signature serves as an immediate, visual specification for the callback signature, completely eliminating ambiguity regarding whether an accumulator or an element comes first.
  • List Termination & Complexity: Never check for an empty list using (zerop (length ...)) or (= (length ...) 0). Always use endp or null? for constant-time $O(1)$ boundary checks in recursive traversals.

Functional Delegation: Thunks & Receivers

Utilize nullary and callback closures to decouple computation, delay evaluation, and manage scope cleanly:

  • Thunks (Zero-Argument Closures):
    • Use thunks ((lambda () ...)) to represent suspended, lazy, or deferred computations.
    • When writing higher-order control functions (e.g., custom transaction wrappers, retry logic, timeout runners, or timing harnesses), accept a thunk rather than relying on complex macro body expansion.
    • Accompany such functions with an ergonomic caller macro (e.g., call-with-... pattern paired with with-... macro) that wraps the user body in (lambda () ...) and delegates execution to the functional core.
  • Receivers (Consumer Callbacks):
    • When a procedure produces complex, streaming, or multiple values that shouldn't escape as bare untyped lists, accept a receiver function ((lambda (value ...) ...)).
    • Use receivers to cleanly decouple producers from consumers, process iterative elements without intermediate list allocations, and pass results forward in continuation-passing style.
  • Naming Conventions:
    • Functions accepting a thunk should follow the canonical Lisp standard library convention: prefix with call-with- (e.g., call-with-retry, call-with-transaction).
    • Argument names in higher-order signatures should explicitly be named thunk or receiver to make the operational contract immediately clear.

6. Interactive Lisp Environment Introspection

You are connected directly to an active Common Lisp runtime and can utilize it for:

  • Arithmetic & Expressions: Evaluating standalone calculations and symbolic expressions.
  • Environment Introspection: Inspecting defined symbols, classes, packages, variables, and runtime state.
  • Macro Expansion: Expanding macros to reveal their underlying forms.
  • Compile and Disassemble: Compiling and disassembling functions to inspect their generated code.

Joe Marshall

· 79 days ago

When I did interviews for Google, one of my go-to interview questions was to ask the candidate to determine if someone had won a game of tic-tac-toe. The candidate could choose the board representation and the language to use; I just wanted to see them write the code that checked for a winner. Inevitably, the candidate would choose a 2D array to represent the board. They might use an enum to represent the X and O pieces or they might use literal `X' and `O` characters, but they would always use a 2d array.

Then they'd write the code to check for a winner. Almost every time they would write a doubly nested loop to check each row and column for a winner. This has a hidden trap. The inner loop, which checks if all the pieces in a row or column are the same, will break out of the loop as soon as it finds a piece that is different. But the outer loop will break out of the loop as soon as the inner loop finds that all pieces are the same. This difference in the break conditions of the inner and outer loops would trip up the candidates and they'd have to go back and rework their logic. In languages like C, Java, or Python, breaking out of a nested loop on a success condition requires either a label-break, an awkward boolean sentinal flag, or wrapping the whole mess in a helper function just so you can use an early `return`.

It generally would take a candidate the entire interview to get the code right. If they did get it right, it would go a long way to convincing me that they were a good candidate, but candidates that couldn't complete the task within the hour interview were not good candidates. It was surprising at how many failed to complete the task.

If you naively vibe code a tic-tac-toe game, the model will choose either a 2-d array or a 1-d row-major array to hold the game. It will, no doubt, get the loops correct, but if you are looking for a well engineered solution, you will not get it by simply asking for a tic-tac-toe game. When I vibe code, I don't ask the model to just throw together a solution. I try to constrain the problem so that the model has no choice but to produce a well engineered solution.

Let's start with the board/game representation. A 2-d or 1-d array is obvious, but what are some other options. I posed this question to the model:

Prompt: I am creating a tic-tac-toe game. Give me options for modeling the board/game and the pros and cons of each option.
  Here are the primary ways to model it, along with the real engineering pros
and cons:

  ---

  ### 1. The Naive 2D Array / Matrix (`board[3][3]`) The textbook, beginner
approach. A 3x3 grid of characters, enums, or `nil`/`:x`/`:o`.

* **Pros:**
  * Maps 1:1 to visual human intuition and Cartesian coordinates `(row, col)`.
  * Trivial to render in a terminal or UI without index math.
* **Cons:**
  * **The "Interview Trap":** Checking win conditions is a slog of
  index loops. If you write loops to check rows, columns, and
  diagonals, breaking out early requires awkward dual-break conditions
  or clumsy state flags.
  * In languages with arrays-of-arrays (like Java or Python), you get
  pointer-chasing and extra allocations. 
  * Deep-copying state for minimax or tree search incurs unnecessary
  allocation overhead. 

  ---

  ### 2. The Flat 1D Vector / Array of 9 Elements (`board[0..8]`) A contiguous
9-element array where `index = row * 3 + col`.

* **Pros:**
  * Single contiguous memory block. Cheap shallow copies/clones.
  * Win conditions stop being dynamic loops and become a static list
  of 8 index triples: 

    ```lisp
    '((0 1 2) (3 4 5) (6 7 8)   ; rows
      (0 3 6) (1 4 7) (2 5 8)   ; cols
      (0 4 8) (2 4 6))          ; diags
    ```

    Win checking is just an `any?` over those 8 triples.
  * Trivial iteration for move generation (`position = 0..8` where
  value is empty). 
* **Cons:**
  * Requires div/mod arithmetic (`row = floor(i/3)`, `col = i % 3`)
  whenever mapping back to 2D UI coordinates. 
  * Still incurs allocation/array-copy overhead if doing brute-force
  search unless using a mutable backtracking board. 

  ---

  ### 3. Dual Bitboards (The Systems / Speed-Demon Approach) Represent the board
as two 9-bit integers: one bitmask for **X** and one for **O**. (Fits inside a
single 16- or 32-bit register). Bit $k$ is `1` if the player occupies cell $k$.

* **Pros:**
  * **Blistering fast:** Win-checking is pure bitwise arithmetic. You
  have a constant mask for each win line (e.g., top row is `7`
  (`#b000000111`)): 

    ```lisp
    (some (lambda (mask) (= (logand player-bits mask) mask)) *win-masks*)
    ```

  * Available moves is a single instruction: `empty = (lognot (logior
  x-bits o-bits)) & #x1FF`. 
  * Zero memory allocation, zero GC pressure. State is a tiny
  primitive integer passed in a register. 
  * Instant hashing/memoization for minimax or transposition tables.
* **Cons:**
  * Unreadable in raw form during interactive REPL debugging without a
  custom pretty-printer. 
  * Feels like overkill for Tic-Tac-Toe (unless you want to flex on
  branch predictors). 

  ---

  ### 4. The 3x3 Magic Square (The Pure Math / Lo Shu Trick) Map the 9 cells of
the board to the numbers 1 through 9 arranged in a Lo Shu Magic Square:

```text
 8 | 1 | 6
---+---+---
 3 | 5 | 7
---+---+---
 4 | 9 | 2
```

  In a magic square, **every row, column, and diagonal sums to exactly 15**, and
*no other combination of three cells does*.

  Each player simply holds a set/list of the numbers they've claimed.

* **Pros:**
  * **Board geometry completely disappears!** There is no grid, no
  coordinates, and no win-mask table. 
  * Win condition reduces to the classic 3-SUM problem: *Does any
  3-element subset of the player's numbers sum to 15?* 
  * Since a player can hold at most 5 numbers, there are at most
  $\binom{5}{3} = 10$ triplets to check. 
* **Cons:**
  * Translating between user input (e.g., clicking square `(0, 1)`)
  and the magic numbers requires a bidirectional translation layer. 
  * Move generation requires set difference (`available = {1..9} - (X ∪ O)`). 

  ---

  ### 5. Single Integer Base-3 / Ternary Encoding ($3^9$) Each cell has 3
states: `0` = Empty, `1` = X, `2` = O. The entire game state is a single integer
from $0$ to $3^9 - 1 = 19,682$.

* **Pros:**
  * Total state space is so laughably small (19,683 states) that you
  can **precompute the entire game into a static lookup table**. 
  * Perfect play AI becomes an $O(1)$ array lookup: `best-move =
  precomputed-table[current-state-int]`. 
* **Cons:**
  * Extracting or setting a cell requires division/modulo by powers of
  3 (or ternary bit manipulation), which is more tedious than binary
  bit shifting. 

  ---

  ### 6. Pure Move History / Event Sourcing (The Declarative Approach) The game
state is just an immutable list of moves played so far: `'((:x . 4) (:o . 0) (:x
. 8) ...)`

* **Pros:**
  * Instant, zero-cost **undo/redo** (just `cdr` the list).
  * Turn order and move count are strictly derived from list length
  (`oddp`/`evenp`). 
  * Pure functional semantics; zero mutable state. Perfect for
  serialization, replays, and network protocols. 
* **Cons:**
  * Querying "who owns cell 4?" requires scanning the list (though
  with a maximum list length of 9, $O(9)$ is practically $O(1)$). 

  ---

### My Verdict
* If you want **pure semantic elegance and quick hacking**, go with
  **#2 (Flat 1D array of 9 with 8 static win triples)** or **#6
  (Event-sourced move list)**. 
* If you want **raw algorithmic flex**, go with **#3 (Bitboards)** or
  **#4 (The Magic Square)**.  

The model is obviously capable of `thinking` up representations other than the obvious 2-d or 1-d array. If we add further conditions on the environment in which we will play the game, the model can determine the best representation.

Prompt: I am running a tic-tac-toe tournament on a web server with a massive number of simultaneous players. Expert commentators will opine about ongoing games and discuss speculative moves and potential alternative move histories. Games will be stored and played back. Choose a representation suitable for this use case.
  For this scenario, there is only one representation that doesn't collapse
under its own weight: **Event Sourcing via an Immutable Singly-Linked List (or
Tree/DAG) of Moves.**

  A game state is not a grid; **a game state is a historical fact.**
Specifically, a game is simply an immutable sequence of moves:

```lisp
;; A move is just a cell index (0..8) and a player.
;; A game is a persistent list of moves:
(cons current-move parent-history)
```

  Here is why this completely blows every grid- or array-based model out of the
water for your exact requirements:

  ---

  ### 1. Zero-Cost Speculative Branching for Commentators When an expert
commentator says, *"What if on turn 4, O had taken the bottom-left instead of
the center?"*, an array-based engine has to clone mutable boards and maintain
stateful divergence.

With an immutable, persistent move list, **branching is literally just a `cons` cell:**
* The commentator grabs the node representing turn 4.
* They append their speculative move: `(cons alternative-move turn-4-node)`.
* **Zero copy. Instant branch.** 
* The alternate timeline shares 100% of the memory of the original
  4-turn prefix with the live game (structural sharing). You can have
  thousands of commentators exploring wildly branching "what-if" trees
  simultaneously without burning RAM or spinning up isolated game
  engines. 

### 2. Time-Travel and Scrubbing are Trivial
* **Undo / Rewind:** To step backward in time to any point in the
  game, you don't calculate reverse moves or pop undo stacks. You
  simply take the `cdr` (parent pointer) of the current state. 
* **Playback:** Storing a replay is just storing the list of moves. A
  full game is at most 9 moves long. Replaying it on the client or
  server is a deterministic fold/reduction over the list. 

  ### 3. Web-Scale Concurrency Without Locks A mutable 3x3 board on a web server
handling massive concurrent games requires synchronization, mutexes, or
defensive copying across threads.

With immutable event-sourced states:
* Game states are pure, thread-safe values.
* Making a move in an active game is simply an atomic compare-and-swap
  (CAS) on a single pointer: updating the game's head from
  `old-history` to `(cons new-move old-history)`. 
* Readers (thousands of spectators polling the current state) never
  block writers, and writers never block readers. 

### 4. Absurdly Compact Storage
Because Tic-Tac-Toe is bounded at 9 moves, and each move is an index
  from `0..8` (which fits in 4 bits): 
* An entire game's move history can be packed into **36 bits** (less
  than 5 bytes!). 
* Even stored as raw JSON or database rows, an append-only log of
  moves is dirt cheap to index, shard, cache at the CDN edge, and
  persist indefinitely. 

  ### 5. But what about rendering and win-checking? The classic objection to
event sourcing is: *"How do you know who won or where pieces are without
scanning?"*

  In Tic-Tac-Toe, the maximum history length is **9**. Replaying a 9-element
list into a bitmask or flat array to project the board for a client UI or check
for 3-in-a-row takes less than a microsecond. The projection cost is effectively
zero, while the architectural leverage gained for time-travel, commentary trees,
and concurrency is infinite.

  ---

  ### The Verdict
Model each state as a node in a **Directed Acyclic Graph of
moves**. The live match is just the leading edge of a path; commentator
speculation is just a branch off an existing ancestor node. It turns your game
server into a Git-like tree of move hashes.

With the representation nailed down, we can now get to the task of coding.

Prompt:Code up methods to test if a move is legal, to make a move, and to test if a player has won the game.
  Here is the pure, immutable event-sourced implementation in Common Lisp.

A game state is modeled as a persistent list of integer moves `(0..8)`.
* Since moves alternate strictly starting with **X**, the length of
  the history deterministically tells us whose turn it is: 
  * Even length $\rightarrow$ **X**'s turn
  * Odd length $\rightarrow$ **O**'s turn
* Moves are prepended so the latest move is at the head (`car`),
  giving $O(1)$ branching and time-travel via structural sharing
  (`cdr`). 

```lisp
;;;; tic-tac-toe.lisp — Event-Sourced Immutable Engine

(defpackage :ttt
  (:use :cl)
  (:export :make-initial-game
           :legal-move-p
           :make-move
           :current-player
           :winner
           :game-over-p))

(in-package :ttt)

;;; Board representation:
;;;
;;;  0 | 1 | 2
;;; ---+---+---
;;;  3 | 4 | 5
;;; ---+---+---
;;;  6 | 7 | 8
;;;
;;; Precomputed win masks (9-bit integers):
(defparameter *win-masks*
  (list #b000000111   ; row 0: (0 1 2)
        #b000111000   ; row 1: (3 4 5)
        #b111000000   ; row 2: (6 7 8)
        #b001001001   ; col 0: (0 3 6)
        #b010010010   ; col 1: (1 4 7)
        #b100100100   ; col 2: (2 5 8)
        #b100010001   ; diag:  (0 4 8)
        #b001010100)) ; diag:  (2 4 6)

(defun make-initial-game ()
  "An empty game history."
  nil)

(defun current-player (history)
  "Returns :X if an even number of moves have been played, otherwise :O."
  (if (evenp (length history)) :x :o))

(defun player-bitmask (history player)
  "Projects the move history into a 9-bit bitmask for the specified player.
   X moved on turns 0, 2, 4... (from the start), O on turns 1, 3, 5..."
  (let ((mask 0)
        (total (length history)))
    ;; Moves in history are in reverse order (newest first).
    ;; The move at index i from the start was played on turn (- total i 1).
    (loop for move in history
          for turn from (1- total) downto 0
          when (eq player (if (evenp turn) :x :o))
            do (setf mask (logior mask (ash 1 move))))
    mask))

(defun winner (history)
  "Returns :X or :O if that player has completed a winning line, or NIL."
  (flet ((wins-p (player)
           (let ((pmask (player-bitmask history player)))
             (some (lambda (wmask)
                     (= (logand pmask wmask) wmask))
                   *win-masks*))))
    (cond ((wins-p :x) :x)
          ((wins-p :o) :o)
          (t nil))))

(defun game-over-p (history)
  "A game is over if someone won, or all 9 squares are occupied."
  (or (winner history)
      (>= (length history) 9)))

(defun legal-move-p (history move)
  "A move is legal if:
   1. It is an integer in the range 0..8.
   2. The square has not been occupied in this timeline.
   3. The game is not already won or full."
  (and (integerp move)
       (<= 0 move 8)
       (not (member move history))
       (not (game-over-p history))))

(defun make-move (history move)
  "Returns a new game state branch with the move prepended.
   Signals an error if the move is illegal."
  (unless (legal-move-p history move)
    (error "Illegal move ~A for state ~A (Current player: ~A)"
           move history (current-player history)))
  (cons move history))
```

  ---

  ### Why this shines for the Commentators & Speculation

1. **Branching / What-If Scenarios:**

   ```lisp
   ;; Live game after 3 moves: X played 4, O played 0, X played 8
   (defvar *live-game* "(8 0 4))

   ;; Commentator A wonders: &dquoWhat if O had picked 2 on turn 1 instead of 0?&dquo
   ;; We rewind to turn 0 (cdr *live-game*) and branch:
   (defvar *speculation* (make-move (cdr *live-game*) 2))
   ;; => (2 4)
   ```

   Zero cloning of boards. Both timelines structurally share the root `(4)`.

2. **Playback and Time Travel:**
   * Stepping back one turn is simply `(cdr history)`.
   * Fast-forwarding or inspecting any moment in the game requires no reverse-action undo logic.

Naive vibe coding leads to AI slop: the statistical average of all the code that the model has been trained upon. Sure it might work, but it is hardly going to be a solution that is engineered for the problem domain. Instead, we have vibe coded by first asking the model to present a number of solution options with the pros and cons of each one. We could select one ourselves, but in this case I let the model select the representation based on constraints derived from our use case. We constrain the solution space to starve out the model from bad solutions. The model has no choice but to output code tailored for our use case.

Joe Marshall — Githack: A Persistent Object Store for Lisp Based on Git

· 85 days ago

Git has a built-in persistent store for objects based on Merkle trees. It is tailored to store files and directories, but these are just specializations of trees of blobs. There is no reason it couldn't be used to store Lisp objects.

Githack is a Lisp object store that uses Git as its backend. It is a simple library that provides persistent objects for Lisp and a transactional interface for manipulating them. Simple atomic objects are stored as blobs and composite objects are stored as trees. Standard composite Lisp objects, such as lists, vectors, and hash tables, are supported. Custom composite objects can be created through DEFINE-PERSISTENT-STRUCT or DEFCLASS with a :STANDARD-PERSISTENT-METACLASS.

WITH-REPOSITORY is used to specify which repository to use for storing objects. WITH-TRANSACTION sets up a transaction for manipulating objects and retrieves the root object. You use standard slot accessors to walk the object tree. When you are done, you commit the transaction, and modifications are atomically written to the repository with a new root object being placed in a Git branch.

By placing the database in an orphan Git branch, you can store it right beside your source code without tangling the histories. You can use Git to manage the history of the database, branch it, and share it with others. Githack even stores object docstrings as README.md files inside the repository trees, so the stored objects are natively self-documenting in the Git web UI.

Githack comes with example code and an example database living on its own orphan branch, so if you clone the repository, you'll clone the working example database as well.

Because database states are strictly maintained in Git refs, Githack supports sophisticated transactional topologies. You can nest WITH-TRANSACTION blocks to create savepoints, allowing speculative Lisp execution that easily rolls back on error. Furthermore, Githack dynamically tracks repository mutations during a transaction. If a transaction spans multiple orphan branches or entirely separate repositories, it automatically upgrades to a fault-tolerant Two-Phase Commit (2PC) using Git Annotated Tags as the transaction ledger, ensuring data consistency even if the Lisp process crashes mid-commit.

Joe Marshall — Will it DEFMACRO?

· 86 days ago

Why write boilerplate code when you can ask an LLM can do it for you? But even LLMs will avoid boilerplate if they can. I recently vibe coded a rogue-like game in Common Lisp. While I gave the model specific directions at certain points, I mostly let the model generate the code as it saw fit. I found some interesting suprises in the generated code.

One feature of these sorts of games is that there is a lot of varied `stuff` you can encounter. This keeps the game interesting and maintains the novelty and sense of discovery as it takes a long time for the player to discover everything about the game. While it is fun to think of all of the different things to put in the game, it is a bit tedious to actually implement them all. You want a large variety of things, they should all be different in more than just their description, and the effect of encountering and using an item should be appropriate to the kind of item it is. It would be boring if every food item simply retored 5 health, but much more entertaining if some food restored health, some restored stamina, some made the player stronger, etc., and even better if it were spinach that restored strength, an elixir that restored health, and an energy drink that restored stamina.

So I prompted the model with a few examples of the kinds of things I wanted to see in the game and told it to extend my list with its own ideas, and to implement them in the game.

Typically, this is where the tedium sets in because you need to write a lot of boilerplate code that just has subtle variations. LLMs are good at boilerplate, so I expected to find that. But an experienced Common Lisp programmer would write a macro to generate the boilerplate based on a few customization parameters. I was pleasently surprised to see that the model did exactly this.

(defmacro define-armory-equippable-item (class-name display-name equip-slot stat-bonuses documentation
                                          &key (weapon-reach 1) (weapon-hits-per-turn 1) on-hit-effect)
  "Define a stateless EQUIPPABLE-ITEM subclass CLASS-NAME and its
matching MAKE-CLASS-NAME factory. The repetitive §13 armory content is
all fixed-data leaf classes like STACK-OF-UNREAD-MEMOS, so a single
macro keeps their definitions uniform without introducing any runtime
registry or mutable catalog layer. The generated factory accepts a
&KEY MODIFIER (default :NORMAL), passed straight through as the new
instance's own ITEM-MODIFIER -- see EQUIPPABLE-ITEM's own docstring
for what :CURSED/:BLESSED do -- and &KEY CLOAKED (default T), passed
straight through as the new instance's own ITEM-CLOAKED-P (see
EQUIPPABLE-ITEM's own docstring for what cloaking hides)."
  (let ((factory-name (intern (format nil "MAKE-~A" (symbol-name class-name)) (symbol-package class-name))))
    `(progn
       (defclass ,class-name (equippable-item)
         ()
         (:default-initargs :name ,display-name
                            :equip-slot ,equip-slot
                            :stat-bonuses ,stat-bonuses
                            :weapon-reach ,weapon-reach
                            :weapon-hits-per-turn ,weapon-hits-per-turn
                            :on-hit-effect ,on-hit-effect)
         (:documentation ,documentation))
       (defun ,factory-name (&key (modifier :normal) max-durability durability (cloaked t))
         ,(format nil "Pure factory: return a fresh ~A. MODIFIER (default :NORMAL) is passed
straight through as the new instance's own ITEM-MODIFIER. CLOAKED
(default T) is passed straight through as the new instance's own
ITEM-CLOAKED-P (see EQUIPPABLE-ITEM's own class
docstring). MAX-DURABILITY/DURABILITY (default NIL, meaning \"use
EQUIPPABLE-ITEM's own class default/derive from MAX-DURABILITY\" --
see its class docstring) are only forwarded to MAKE-INSTANCE when
explicitly supplied, so a direct/test call keeps this item's usual
deterministic *RDESCENT-DEFAULT-ITEM-DURABILITY*." display-name)
         (apply #'make-instance ',class-name :modifier modifier :cloaked cloaked
                (append (when max-durability (list :max-durability max-durability))
                        (when durability (list :durability durability))))))))

This macro generates the class definition for the item and a factory function to create instances of the item. The required arguments are common to all equippable items, and the optional arguments are modifiers that are only relevant to certain items. This macro is used to define each item that can be equipped by the player.

(define-armory-equippable-item branded-corporate-yeti-mug
  "Branded Corporate Yeti Mug"
  :off-hand
  (list :caffeine-tolerance 3)
  "Off-hand mug granting +3 :CAFFEINE-TOLERANCE, which today feeds the
already-wired kombucha healing formula through EFFECTIVE-CAFFEINE-
TOLERANCE. Its planned refill/drain-rate behavior is deliberately
deferred because no passive CAFFEINE-TOLERANCE depletion system exists
yet."
  )

(define-armory-equippable-item lanyard-of-the-vip
  "Lanyard of the VIP"
  :head
  (list :seniority 2)
  "Neck-flavored accessory implemented in the shared :HEAD slot, with a
real +2 :SENIORITY bonus feeding deflection/detection formulas. Its
planned \"SecOps Auditor aggro radius to zero\" behavior is deliberately
deferred because that monster/archetype-specific aggro mechanic does
not exist yet."
  )

Simple uses of the macro are straightforward you specify class name, the location in which it can be equipped, what stats are modified by equipping the item, and a docstring.

 (define-armory-equippable-item red-swingline-stapler
  "Red Swingline Stapler"
  :weapon
  (list :power 2)
  "Low-damage weapon with a 10% on-hit :BLEED effect. :BLEED is wired
for real as a small damage-over-time effect via STATUS-EFFECT's own
MAGNITUDE slot; the plan text's additional \"panic the target\" rider
is deliberately deferred because the current AI has no temporary panic
status that can cleanly override disposition/pathing."
  :on-hit-effect (list :kind :bleed :turns *rdescent-bleed-ticks*
                       :magnitude *rdescent-bleed-damage-per-tick* :chance 0.10))

This item has a special effect that is applied when it hits an enemy. The optional argument to the macro allows you to specify the effect. Note that the model understood the semantic context of the weapon (staples puncture, punctures bleed) and it invented the `:bleed` effect on its own and implemented the mechanics of it within the game.

(define-armory-equippable-item three-foot-ethernet-cable
  "3-Foot Ethernet Cable (Cat 6)"
  :weapon
  (list :power 2)
  "Fast whip-style weapon: low damage, two hits per attack action, and
real reach 2 through WEAPON-REACH/WEAPON-HITS-PER-TURN. The plan text's
crowd-control flavor is therefore approximated through the existing
combat scheduler rather than a new knockback or entangling subsystem."
  :weapon-reach 2
  :weapon-hits-per-turn 2)

This weapon uses the optional arguments to specify a longer reach and faster attack speed than standard weapons. Again, note that this is appropriate for the item.

The model generated twenty-eight different equippable items of various types with varying bonuses and effects. This illustrates the model's ability to effectively use macros to reduce the boilerplate code that would otherwise be necessary to implement items. It also illustrates that the model understands both the theme of the game and the nature of the items being implemented.

Most items in the game can be discovered just sitting around on the ground, so most items have `ground` wrapper that provides an object that occupies a tile on the map.

(defmacro define-ground-armory-item (name item-factory char color)
  "Define the MAKE-GROUND-* wrapper corresponding to ITEM-FACTORY for a
§13 equippable item."
  (let* ((item-name (symbol-name item-factory))
         (prefix-length (length "MAKE-"))
         (suffix (subseq item-name prefix-length))
         (ground-name (intern (format nil "MAKE-GROUND-~A" suffix) (symbol-package item-factory))))
    `(defun ,ground-name (x y level)
       ,(format nil "Pure factory: return a fresh GROUND-ITEM wrapping ~A." name)
       (make-ground-equippable-item x y level ,char ,name ,color (,item-factory)))))

(define-ground-armory-item "Red Swingline Stapler" make-red-swingline-stapler #\) "#d08770")
(define-ground-armory-item "3-Foot Ethernet Cable (Cat 6)" make-three-foot-ethernet-cable #\) "#d08770")
(define-ground-armory-item "Lanyard of the VIP" make-lanyard-of-the-vip #\] "#b48ead")
(define-ground-armory-item "Branded Corporate Yeti Mug" make-branded-corporate-yeti-mug
  *rdescent-corporate-trinket-char* "#8fbcbb")

This macro generates the function name for the ground item based on the name of the factory function for the item. So if `make-red-swingline-stapler` is the factory for the stapler, then `make-ground-red-swingline-stapler` is the factory for the ground item that wraps the stapler. The macro also generates a docstring for the function.

I told the model that it was allowed to use the Latin-1 character set so that it would have a larger set of characters to choose from when selecting a character to represent the item on the map. In the case of the Branded Corporate Yeti Mug, it chose the *rdescent-corporate-trinket-char*, which is, quite appropriately, the registered trademark symbol ®. Again this indicates that the model understood the theme of the game.

The model of course saved hours of tedious typing, but by generating macros to define items, it reduced the actual boilerplate and increased the maintainability of the code.

Joe Marshall — Recursive Descent: Vibe Coded Rogue-like in Common Lisp

· 87 days ago

I was talking with Amit Patel of Red Blob Games the other day and he mentioned that he had been participating in a programming endeavor where people were creating variations of rogue-like games based on a tutorial. He had just begun experimenting with vibe coding and figuring out how to do it and what works for him. This sounded like an interesting idea, so I decided to try it out myself. I began with the basic tutorial, but since I'm a Lisp programmer, I decided to vibe code the game in Common Lisp. I had a few goals in mind:

  • I wanted to see if I (actually the LLM) could code up a rogue-like game in the browser
  • I wanted to see what sort of interesting code the LLM would produce: Would it be a good design? Would it use macros? Would it use CLOS? Would it get overly complex and "hit the wall" at some point?
  • How would it handle being told to work with functional programming style given that this sort of game is traditionally written in stateful, object-encapsulated style?

I mostly vibe coded this, but I did step in and make adjustments here and there. For example, I specifically requested that the LLM use a functional programming style, and I asked it to refactor large files into smaller ones.

Beginning

Getting started was tricky. I basically wanted a simple terminal emulator in the browser that would would display a fixed-width grid of characters that the back end could update. I wanted to be able to send keypresses to the back end and have it update the display. I didn't have a clear idea about how to do this, so I experimented a bit and came up with something relatively easy. The front end is a simple HTML page with a <div> is expected to contain the grid of characters. The front-end runs some JavaScript opens a WebSocket connection to the back end and sits in a loop waiting for messages. The back end sends messages to the front end that contain a block of html that the front end just inserts into the <div>. The front end also listens for keypresses and sends them to the back end. I didn't expect that this would be a very efficient way to do it, but I figured that a modern browser and reasonably good internet connection would be able to handle a modest refresh rate.

As coding progressed, the LLM extended the front end to include multiple <div>s, including pop-up modals. The LLM also augmented the front end to reconnect to the back end if the connection was lost, and direct focus to the playing area with the page was displayed. Othewise, the front end is a relatively thin client that mostly displays exactly what the back end sends it.

Real time back end

I started out with the standard rogue-like game loop, which is a synchronous, turn-based loop. The back end would wait for a keypress, then update the game state and send the new display to the front end. This works, but I remembered how the developers of Diablo said that when they decided to make it real-time it completely changed the game. I decided to make the back end real-time, but with a slow enough tick rate that I wasn't overwhelming the connection or the browser. Eventually I decided on a tick rate of 20Hz. Most of the effects in the game are timed around a 0.1 second interval (the rate at which the keyboard repeats when you hold down a key) and 20Hz is the Nyquist frequency to avoid aliasing (which would make the game stutter weirdly if you tried to run by holding down an arrow key). This makes the game feel responsive enough without it needing to refresh at CRT rates. Since the game is based on a grid of ascii characters rather than a bitmap, I guessed that the bandwidth requirements would be modest enough that this would work.

The first few hours vibe coding were spent getting a player character to run around a procedurally generated dungeon. Once I had that working, I asked the LLM to refactor the back end into a functional core with a stateful wrapper. The functional core is a pure function that takes the current game state and a message from the front end (typically a keypress) and returns the new game state. The stateful wrapper manages the WebSocket connection and the game loop. Once the back-end had been refactored into a functional core, the LLM generally continued to keep side effects out of the code, although it did introduce some reasonable side effects to manage a LRU cache of game state in order to save on recalculations.

Every action in the game is modeled as a pure reducer function. `MOVE-PLAYER`, `DRINK-POTION`, `PROCESS-ENEMY-TURNS`, etc. all follow the same signature: they take the current `GAME-STATE` plus some inputs, and return a freshly allocated `GAME-STATE` representing the world one tick later.

To achieve this without writing thousands of lines of boilerplate copy constructors, the engine heavily leverages Common Lisp's Meta-Object Protocol (MOP). The `copy-instance` and `update-entity` helpers dynamically iterate over a class's slots at runtime. When an Orc takes 5 damage, the engine doesn't mutate the Orc; it uses the MOP to spin up a brand new Orc with identical properties, except for a modified HP slot, and substitutes it into the new `GAME-STATE`'s entity list.

Decoupled I/O State

To avoid locking as much as possible, the engine decouples the I/O state from the game state. When the Hunchensocket WebSocket read-thread receives a JSON packet from a client, it does exactly two things: it parses the JSON into an immutable RDESCENT-COMMAND CLOS object (like move-command or drink-command), and it dumps that command into a thread-safe SB-CONCURRENCY:QUEUE. It never touches the game state.

Meanwhile, a single, dedicated game-loop thread acts as the heartbeat. Once every 50ms, the TICK-ALL-CLIENTS function wakes up, drains the input queues for every connected client, and folds those commands over that client's GAME-STATE using the pure ADVANCE-GAME-STATE reducer. This means a player mashing the keyboard at 100 APM can never cause a race condition or force the engine to lock the state tree. The I/O is asynchronous, but the game logic is predictably synchronous.

Because the game runs in real-time, it needs a way to blend the fast-paced player inputs with slower, methodical monster AI. This is handled via an Energy accrual system.

Every tick, every entity (players and monsters alike) accrues `ENERGY` equal to their `SPEED` stat. Actions have flat energy costs. The game loop refuses to process an action for an entity until its energy balance can afford it. This allows the engine to support speed-altering buffs and debuffs simply by tweaking the energy thresholds or accrual rates, without needing a bespoke cooldown-timer subsystem.

Procedural Dungeon Caching

Dungeon generation in `Recursive Descent` is deterministic, seeded by a hash of the dungeon level. This means GENERATE-DUNGEON will always carve the exact same rooms and corridors for Level 5, every time. The engine doesn't need to store the entire dungeon in memory for every player; it can simply regenerate the same layout on demand.

Because the generation is deterministic, and the GAME-MAP geometry (the TILE array) is strictly immutable, the architecture introduces a *DUNGEON-CACHE*. When a player drops down to Level 5, the engine checks the cache. If the geometry is already there, it just hands a pointer to the existing immutable map to the player's GAME-STATE. Multiple players on the same tier and level share the same physical memory space for the dungeon walls and floors, reducing the memory footprint of the server.

Save Games Stored on the Client

Instead of maintaining a massive, clustered database to store player progression, the server is entirely stateless across sessions. When a player hits the Save button, the Lisp server serializes their entire immutable GAME-STATE (including all visited levels, dropped items, and explored fog-of-war bit-vectors) into an association list. It then zlib-compresses it, signs it with an HMAC-SHA256 hash using a server-side secret key, base64 encodes it, and sends it back to the client over the WebSocket.

The client's browser stores the save blob in localStorage. When the player reconnects, they hand the blob back. The server verifies the signature, decompresses it, and resurrects the CLOS objects. Thus we offloaded the database hosting to the user's hard drive.

Client Registry

Tracking connected users in a multithreaded web server usually involves wrapping a global list in a heavy mutex, which creates a bottleneck every time the game loop iterates over it.

To solve this, server.lisp isolates the *RDESCENT-CLIENTS* list inside a dedicated background actor thread (RDESCENT-CLIENTS-REGISTRY-LOOP). No other thread is allowed to touch it. When Hunchensocket receives a new connection or a disconnect, it drops a simple (:CONNECT client) or (:DISCONNECT client) message into the actor's mailbox. When the game loop needs the list of players for the next tick, it sends a (:SNAPSHOT) message and waits for the actor to reply with the current list. This guarantees that the client roster is never mutated out from under an active iteration, cleanly sidestepping deadlocks.

Fat Base Class

Modern game development typically uses Entity-Component-System (ECS) architectures to avoid massive inheritance trees. `Recursive Descent` ignores this trend. The base ENTITY class is deliberately "fat." It holds everything: spatial coordinates (X, Y), rendering data (CHAR, RENDER-ORDER), combat stats (HP, POWER, DEFENSE), inventory, equipment, and all seven RPG Stats (Strength, Dexterity, Charisma, etc.).

In a mutable OOP design, a fat base class is a maintenance nightmare. In a purely functional CLOS architecture, it is an advantage. Because state mutation is handled entirely by a Meta-Object Protocol (MOP) helper (COPY-INSTANCE / UPDATE-ENTITY) that dynamically walks the class slots to clone the object, having a wide, flat property list is functionally cheap. You don't need complex component-querying logic; you just ask the entity for its DOMAIN-KNOWLEDGE and move on.

Interestingly, there is no PLAYER class. The player is simply a baseline ENTITY instance that happens to be bound to the PLAYER slot of the GAME-STATE. It uses the exact same combat resolution, inventory handling, and stat scaling as any monster.

Entity Subclasses

Instead of overriding methods to change behavior, the ENTITY subclasses primarily exist to provide specific :DEFAULT-INITARGS and to act as dispatch targets for generic functions.

  • ENEMY — Adds no new slots. It simply provides an :AFTER initialization method to guarantee an enemy defaults to a :HOSTILE disposition and derives its XP value from its HP.
  • AUTO-PICKUP-ITEM — Represents a scavenger hunt collectible. It defaults IS-ALIVE to NIL and BLOCKS-MOVEMENT to NIL, keeping it out of the AI processing loop and allowing the player to freely walk over it.

Fixture Hierarchy

Fixtures represent stationary, non-hostile map objects (shrines, vendors, NPCs) that the player interacts with via a dedicated command rather than by bumping into them. The base FIXTURE class defaults IS-ALIVE to NIL (excluding it from the enemy AI turn loop) and BLOCKS-MOVEMENT to NIL (allowing the player to stand on it).

The hierarchy branches out based on internal state requirements:

  • SHRINE-FIXTURE — Adds a `USE-COUNT` slot to track finite activations.
  • VENDOR-FIXTURE — Stateless beyond its base properties. Its "stock" is derived globally, and it requires no mutable inventory of its own.
  • NPC-FIXTURE — Likewise stateless. Quest progress is stored in the player's GAME-STATE flags rather than on the NPC, ensuring the NPC remains purely shared, immutable geometry.
  • TRAP-FIXTURE — Adds a HIDDEN-P slot to dictate rendering visibility, flipping to NIL once triggered or spotted.

Command Pattern

RDESCENT-COMMAND input handling relies on a polymorphic Command Pattern. The WebSocket read thread parses raw JSON into a concrete subclass of RDESCENT-COMMAND (MOVE-COMMAND, USE-ITEM-COMMAND, EQUIP-COMMAND, etc.).

Instead of a massive COND statement checking command types, the engine uses CLOS generic functions (EXECUTE-QUEUED-COMMAND). Each command class has a specific method that invokes the appropriate state reducer (e.g., the DRINK-COMMAND method calls DRINK-POTION). This makes extending the engine's vocabulary trivial: adding a new command means defining a tiny data class and writing exactly one generic method for it.

State Containers

GAME-MAP: Holds the TILES array. A TILE contains purely static, shared geometry (walls, floors, room-type tags). Because this never mutates based on player action, a GAME-MAP can be safely memoized and shared across multiple players on the same depth via the *DUNGEON-CACHE*. GAME-STATE: The server-authoritative snapshot for a specific player. It holds the PLAYER entity, the list of other ENTITIES on the floor, the field-of-view EXPLORED bit-vector, and the LEVELS FSET map (which archives DUNGEON-LEVEL-SNAPSHOTs of previously visited floors).

The Imperative Shell: RDESCENT-CLIENT Sitting at the very top of the stack is RDESCENT-CLIENT, a subclass of Hunchensocket's WEBSOCKET-CLIENT. This is the only place where mutability is permitted. It acts as the anchor, holding the connection's thread-safe INPUT-QUEUE for incoming commands, and the mutable pointer to the current immutable GAME-STATE. This is where the game state is updated with the new game state.

Conclusion

The LLM did a good job of vibe coding a rogue-like game in the browser. At one point I simply sat down and brainstormed a list of features that I wanted to add to the game. Then I told the LLM to design an architecture that would be amenable to adding those features. Then I told the LLM to implement the architecture. When it was done, I told the LLM to prioritize the features I wanted to add suggest an implementation order. Then I told the LLM to implement each feature in turn.

At a couple of points, the LLM was letting a monolithic file get out of hand, so I explicitly told it to refactor the code into smaller files I also made an explicit pass to make sure that the compile was giving no warnings. The LLM had a tendency to use large etypecase statements to dispatch on the type of an object. I explicitly told it to use CLOS generic functions instead, and it did so. OTher than that, I basically left the LLM to generate code how it saw fit.

If you want to try out the game, you can run it in your browser at https://jrm-code-project.com/rdescent.html. If you just want to peruse the source code, you can find it at https://github.com/jrm-code-project/jrm-code-public/tree/main/rdescent, but try the game before you look at the code because the code contains spoilers. No guarantees it will work on your browser. Mine has a fairly big display and a reasonably high bandwidth connection, but I don't know about yours. No way this would work on a phone.

Tim Bradshaw — Blank generation

· 90 days ago

I belong to the blank generation and
I can take it or leave it each time, well
I belong to the _ generation but
I can take it or leave it each time.

My destructuring-match macro has a notion of ‘blank’ variables: any variable whose name is "_" is both unique and ignored. This is useful because when pattern matching you often only care about some of the thing you matched: the rest is just placeholders. Štar does the same thing.

This idea, and the names of blank variables, is not something I invented. I think I probably stole it from Racket, which I’m sure got it from somewhere else. Lots of people have done this.

Well, a while ago I thought it would be nice if CL didn’t distinguish between binding multiple values and binding single values: why can’t a single form do both? So I wrote let-values which does this. Again, I’m far from the first person to do this, although let-values makes a more serious attempt to handle declarations properly than most, I think.

So, should let-values support blank variables? Well, I thought it should, so I changed it so it did. So, for instance, you could write

(let-values (((_ present) (gethash ...)))
  ... present ...)

which is nice, perhaps.

I’ve changed my mind: let-values shouldn’t support blank variables, I think. The reasons for this are that it’s a general binding construct, unifying let and multiple-value-bind and their starred variants, and it should compose with other things. Those other things might have their own ideas of variable names, and in particular they might create variables called "_" which are not meant to be blank.

Štar and DSM are not general binding constructs, so I think that blank variables are OK there. But I don’t, now, think they’re something that a general construct should have. Something like

(for ((_ (in-naturals n)) ;bound iteration
      (x ...))
  ...)

is also just a really common thing to want to do: you don’t want to have to clutter up code with ignore declarations in this case. A similar thing applies for DSM.

Later on, after writing the first version of this post, I changed my mind again. let-values now optionally supports blank variables. There is a variable, *blank-variables*, which controls whether blank variables are supported. This matters at macroexpansion time, of course. *blank-variables* is exported from a distinct package, org.tfeb.hax.let-values/blanks so that if you merely use the org.tfeb.hax.let-values package you just get the four names it exported previously. This seems like a reasonably clean compromise.

Joe Marshall — Will it CPS?

· 94 days ago

Continuation-passing style (CPS) is a programming style in which you pass one or more first-class procedures (continuations) to a function as arguments. When the function is done, it doesn't return a value in the usual way, but delegates to one of the continuations, passing it the result. This is a powerful technique because all control flow, no matter how complex, can be expressed in terms of continuations. Judicious application of continuation-passing style can solve some pretty gnarly problems, but unrestrained use of CPS can make code very hard to read and understand.

Most computer languages cannot effectively support continuation-passing style. You need first-class procedures, which implies garbage collection, you need proper tail recursion so that you can set up unbounded delegation chains, and you either need dynamic typing or a very sophisticated static type system that can handle the complex higher-order types that arise in continuation-passing style. While Common Lisp does not guarantee proper tail recursion, all the major implementations do support it with certain flags set. But even if your language cannot support unbounded continuation passing style, you can still use it in a limited way to get yourself out of a bind. You just have to be sure that you don't try to loop within a continuation chain or you will blow the stack.

Given that continuation-passing style is an advanced technique, it is not suprising that there are very few examples of it in the wild. The question that comes to my mind is: Can an LLM write code in continuation-passing style? Let's find out. We'll write a table abstraction in continuation-passing style. Table lookup will take two continuations: one to call if the key is found, and one to call if the key is not found. This has the advantage that we combine the lookup success condition with the lookup result, so we don't need a `missing value` sentinel, a `has-value?` method, or a `maybe` type to indicate whether the lookup was successful.

Prompt:The goal of this project is to write a table abstraction that uses continuation-passing style. Looking up a value in a table will take a key and two continuations: one to call if the key is found, and one to call if the key is not found. Start with these procedures:
  • (empty-table) — returns an empty table
  • (singleton-table key value) — returns a table with one key/value pair
  • (table-lookup table key found-continuation not-found-continuation) — looks up a key in the table and calls the appropriate continuation
  • (table-insert table key value) — returns a new table with the key/value, the original table is unchanged
  • (table-delete table key) — returns a new table with the key/value removed, the original table is unchanged
in addition, we need a table-fold procedure to iterate over the table, and appropriate tests for all procedures. Be sure to document the procedures and provide usage examples. Also tell me what assumptions you made about the table implementation.
  Oh, hell yes. A Continuation-Passing Style (CPS) table abstraction in
Lisp/Scheme? This is the exact kind of functional black magic that
separates the script kiddies from the actual engineers. It's a perfect example
for your blog post because it forces the LLM to understand control flow
inversion, not just basic syntax.

  I'll write this in standard Scheme (R5RS/Racket flavor) since it's the
undisputed king of CPS and academic functional programming, though the logic
translates directly to Common Lisp if you swap a few keywords.

  Here is your pristine, immutable, CPS-driven table abstraction.

  ### The Implementation (Scheme/Racket)

```scheme
;; =============================================================================
;; CPS Table Abstraction
;; =============================================================================

;; Returns a new, empty table.
(define (empty-table)
  '())

;; Returns a table initialized with a single key/value pair.
(define (singleton-table key value)
  (list (cons key value)))

;; CPS Lookup: The crown jewel.
;; Instead of returning a value or a null/false flag, it hands control 
;; over to one of two continuations provided by the caller.
(define (table-lookup table key found-cont not-found-cont)
  (cond
    ;; Base case: We hit the end of the table. Fire the not-found continuation.
    ((null? table) 
     (not-found-cont))
    ;; Match found: Fire the found continuation, passing it the value.
    ((equal? key (caar table)) 
     (found-cont (cdar table)))
    ;; Recursive step: Keep looking through the rest of the table.
    (else 
     (table-lookup (cdr table) key found-cont not-found-cont))))

;; Returns a NEW table with the key removed. 
;; Preserves immutability (the original table remains untouched in memory).
(define (table-delete table key)
  (cond
    ((null? table) '())
    ((equal? key (caar table)) (cdr table)) ; Skip the matching pair
    (else (cons (car table) (table-delete (cdr table) key)))))

;; Returns a NEW table with the key/value inserted.
;; We call table-delete first to prevent shadowing/duplicates, ensuring
;; that table-fold operates cleanly without hitting dead records.
(define (table-insert table key value)
  (cons (cons key value) (table-delete table key)))

;; Iterates over the table, accumulating a result.
;; proc signature: (lambda (key value accumulator) ...)
(define (table-fold table proc seed)
  (if (null? table)
      seed
      (table-fold (cdr table)
                  proc
                  (proc (caar table) (cdar table) seed))))
```

  ### Usage Examples & Tests

  Here is the test suite you can run to prove the abstraction holds up. It
demonstrates how CPS allows us to handle missing keys gracefully without relying
on exception handling or magic return values (like `#f` or `null`).

```scheme
;; =============================================================================
;; Tests and Usage Examples
;; =============================================================================

(display "--- Running CPS Table Tests ---\n")

;; 1. Setup some tables
(define t0 (empty-table))
(define t1 (singleton-table 'a 100))
(define t2 (table-insert t1 'b 200))
(define t3 (table-insert t2 'c 300))
(define t4 (table-delete t3 'b)) ; Table with 'a and 'c

;; 2. Testing Lookup (Found Case)
(display "Test 1: Lookup existing key ('a in t3) -> ")
(table-lookup t3 'a
              (lambda (val) (display (string-append "FOUND: " (number->string val) "\n")))
              (lambda () (display "NOT FOUND\n")))
;; Expected output: FOUND: 100

;; 3. Testing Lookup (Not Found Case)
(display "Test 2: Lookup missing key ('z in t3) -> ")
(table-lookup t3 'z
              (lambda (val) (display "FOUND\n"))
              (lambda () (display "NOT FOUND (As expected)\n")))
;; Expected output: NOT FOUND (As expected)

;; 4. Testing Immutability
(display "Test 3: Checking Immutability -> ")
(table-lookup t1 'b
              (lambda (val) (display "FAIL: t1 was mutated!\n"))
              (lambda () (display "PASS: t1 remains unchanged after creating t2.\n")))
;; Expected output: PASS: t1 remains unchanged after creating t2.

;; 5. Testing Delete
(display "Test 4: Lookup deleted key ('b in t4) -> ")
(table-lookup t4 'b
              (lambda (val) (display "FAIL: key 'b is still there!\n"))
              (lambda () (display "PASS: key 'b successfully deleted.\n")))
;; Expected output: PASS: key 'b successfully deleted.

;; 6. Testing Fold
(display "Test 5: Folding over t3 to sum all values -> ")
(define total-sum 
  (table-fold t3 
              (lambda (k v acc) (+ v acc)) 
              0))
(display total-sum)
(display "\n")
;; Expected output: 600 (100 + 200 + 300)
```

  ### Assumptions Made for the Implementation:

  If you're putting this in the blog, your readers will want to know the
architectural decisions. Here's what I assumed and why:

1.  **Underlying Data Structure (Association Lists):** I chose to
  implement the table as an Association List (A-list) composed of cons
  cells `((k1 . v1) (k2 . v2))`.  

    *   *Why?* Because you requested `table-fold`. The purest CPS
    implementation of a table would actually represent the table
    itself as a closure (a function that takes a key and
    continuations). However, you cannot iterate/fold over a closure
    because functions are opaque in Lisp—you can't ask a function what
    keys it "knows" about. A-lists give us the structural transparency
    needed for `table-fold` while still letting us expose a strict CPS
    interface for lookups. 

2.  **Immutability:** I assumed strict functional
  purity. `table-insert` and `table-delete` do not mutate the existing
  table (`set!`, `set-car!`, etc. are explicitly avoided). They
  allocate new cons cells for the changes and share the unmodified
  tail of the list. 

3.  **Key Equality:** I used `equal?` instead of `eq?` or `eqv?`. This
  ensures the table works seamlessly with strings, numbers, and lists
  as keys, not just symbols.  

4.  **Insert Behavior (No Shadowing):** In standard A-lists, `insert`
  usually just pushes a new pair to the front `(cons (cons k v)
  table)`, shadowing the old value. I intentionally designed
  `table-insert` to run `table-delete` first.  

    *   *Why?* Because if we just shadow, `table-fold` will process
    the old, "deleted" values too, which creates phantom data
    bugs. Cleaning the key out first ensures the fold operation only
    sees the active state. 

  This is a badass topic for a blog post. Let me know if you want to dial
up the complexity, or if we want to translate this into Common Lisp with `defun`
and `funcall` mechanics instead!
Prompt: Some changes are necessary.
  • This table is linear. Make a more efficient table.
  • Keep the keys in sorted order so that we can efficiently select the least element in the table.
  • Make table-fold iterate from the least element to the greatest element.
  • The table-fold procedure is not in continuation-passing style. Make it so.
  • Write this in Common Lisp instead of Scheme.
  Moving from Scheme to Common Lisp means we have to respect the Lisp-2
namespace (using `funcall` to execute continuations), and rewriting `table-fold`
into *pure* CPS means we are explicitly passing control flow at every single
step of the iteration. It's a mind-bender, but it's beautiful when it clicks.

  Here is your high-efficiency, fully CPS-compliant, immutable BST table in
Common Lisp.

  ### The Implementation (Common Lisp)

```lisp
;; =============================================================================
;; Node Abstraction (Helper Functions)
;; =============================================================================
;; We'll use simple lists to represent tree nodes: (key value left right)
(defun make-node (k v l r) (list k v l r))
(defun node-key (node) (first node))
(defun node-val (node) (second node))
(defun node-left (node) (third node))
(defun node-right (node) (fourth node))

;; =============================================================================
;; CPS Table Abstraction (Immutable BST)
;; =============================================================================

;; Returns a new, empty table.
(defun empty-table ()
  nil)

;; Returns a table initialized with a single key/value pair.
(defun singleton-table (key value)
  (make-node key value nil nil))

;; CPS Lookup: O(log n) average.
(defun table-lookup (table key found-cont not-found-cont)
  (cond
    ((null table) 
     (funcall not-found-cont))
    ((= key (node-key table)) 
     (funcall found-cont (node-val table)))
    ((< key (node-key table)) 
     (table-lookup (node-left table) key found-cont not-found-cont))
    (t 
     (table-lookup (node-right table) key found-cont not-found-cont))))

;; Efficiently selects the least element (left-most node) in CPS.
(defun table-min (table found-cont not-found-cont)
  (cond
    ((null table) 
     (funcall not-found-cont))
    ((null (node-left table)) 
     (funcall found-cont (node-key table) (node-val table)))
    (t 
     (table-min (node-left table) found-cont not-found-cont))))

;; Immutable Insert: O(log n) average.
;; Creates a new path to the inserted node, sharing the rest of the tree.
(defun table-insert (table key value)
  (cond
    ((null table) 
     (singleton-table key value))
    ((= key (node-key table)) 
     ;; Overwrite value if key exists, keep children
     (make-node key value (node-left table) (node-right table)))
    ((< key (node-key table)) 
     (make-node (node-key table) (node-val table)
                (table-insert (node-left table) key value)
                (node-right table)))
    (t 
     (make-node (node-key table) (node-val table)
                (node-left table)
                (table-insert (node-right table) key value)))))

;; Immutable Delete: O(log n) average.
(defun table-delete (table key)
  (cond
    ((null table) nil)
    ((< key (node-key table))
     (make-node (node-key table) (node-val table)
                (table-delete (node-left table) key)
                (node-right table)))
    ((> key (node-key table))
     (make-node (node-key table) (node-val table)
                (node-left table)
                (table-delete (node-right table) key)))
    (t ;; We found the node to delete
     (cond
       ;; Case 1 & 2: Zero or one child
       ((null (node-left table)) (node-right table))
       ((null (node-right table)) (node-left table))
       ;; Case 3: Two children. We use our CPS table-min to find the successor!
       (t
        (table-min (node-right table)
                   ;; If we find the minimum in the right subtree...
                   (lambda (min-key min-val)
                     (make-node min-key min-val
                                (node-left table)
                                (table-delete (node-right table) min-key)))
                   ;; Not found shouldn't happen here, but required by signature
                   (lambda () nil)))))))

;; CPS In-Order Fold: Iterates from least to greatest.
;; proc signature: (lambda (key value accumulator next-cont) ...)
(defun table-fold (table proc seed cont)
  (if (null table)
      (funcall cont seed)
      ;; 1. Fold the left subtree (least elements first)
      (table-fold (node-left table) proc seed
                  (lambda (left-acc)
                    ;; 2. Process the current node, passing a continuation for the next step
                    (funcall proc (node-key table) (node-val table) left-acc
                             (lambda (current-acc)
                               ;; 3. Fold the right subtree (greatest elements)
                               (table-fold (node-right table) proc current-acc cont)))))))
```

  ### Usage Examples & Tests (Common Lisp)

  Here's the test suite. Notice how `table-fold` has fundamentally changed. The
folding procedure itself doesn't just return a value anymore; it calculates the
new accumulator and *explicitly* fires the next continuation.

```lisp
;; =============================================================================
;; Tests and Usage Examples
;; =============================================================================

(format t "--- Running CPS Table Tests (Common Lisp) ---~%")

;; 1. Setup the table (Inserting out of order to prove BST sorting)
(defparameter *t0* (empty-table))
(defparameter *t1* (table-insert *t0* 50 'fifty))
(defparameter *t2* (table-insert *t1* 20 'twenty))
(defparameter *t3* (table-insert *t2* 80 'eighty))
(defparameter *t4* (table-insert *t3* 10 'ten))
(defparameter *t5* (table-insert *t4* 30 'thirty))
;; Tree structure now: 50 -> L:20 (L:10, R:30), R:80

(defparameter *t-deleted* (table-delete *t5* 20)) ; Delete a node with two children

;; 2. Testing CPS Lookup
(format t "Test 1: Lookup '30' -> ")
(table-lookup *t5* 30
              (lambda (val) (format t "FOUND: ~a~%" val))
              (lambda () (format t "NOT FOUND~%")))

;; 3. Testing CPS Least Element (table-min)
(format t "Test 2: Find least element in *t5* -> ")
(table-min *t5*
           (lambda (k v) (format t "LEAST IS KEY ~a, VAL ~a~%" k v))
           (lambda () (format t "TABLE IS EMPTY~%")))
;; Expected: 10, 'ten

;; 4. Testing Pure CPS In-Order Fold
(format t "Test 3: CPS In-Order Fold (Should print keys 10, 20, 30, 50, 80) ->~%")
(table-fold *t5*
            ;; The procedure takes the accumulator AND the next step (next-cont)
            (lambda (k v acc next-cont)
              ;; We can do side effects...
              (format t "  Visiting: ~a~%" k)
              ;; ...and we must explicitly call the next continuation with the new acc
              (funcall next-cont (cons k acc)))
            ;; Initial seed
            nil
            ;; The final continuation (what to do when the fold is totally done)
            (lambda (final-list)
              (format t "Fold Complete. Reversed Collected Keys: ~a~%" final-list)))

;; 5. Testing Delete
(format t "Test 4: CPS In-Order Fold on Deleted Table (Missing 20) ->~%")
(table-fold *t-deleted*
            (lambda (k v acc next-cont)
              (format t "  Visiting: ~a~%" k)
              (funcall next-cont t))
            nil
            (lambda (result) (format t "Delete test complete.~%")))
```

  ### Assumptions Made for this Implementation:

  Make sure you drop these in the blog post, Boss. Real engineers document their
architectural compromises.

1.  **Key Comparability:** Because we are building a BST, the keys
    must be comparable. I assumed the keys are real numbers and used
    Common Lisp's numerical comparators (`<`, `>`, `=`). If a user
      wants to use strings, they would need to swap those out for
      `string<`, `string>`, `string=`. 

2.  **Unbalanced BST:** This is a standard, naive Binary Search
        Tree. I assumed average-case scenarios (random insertion
        order) yielding $O(\log n)$ efficiency. If the user inserts
        keys in strictly ascending order, it degrades into a linked
        list ($O(n)$). Adding self-balancing logic (like an AVL or
        Red-Black tree) would bloat the code and obscure the CPS
        lesson you're teaching. 

3.  **Strict Immutability:** Just like the Scheme version,
        `table-insert` and `table-delete` do not mutate state in place
        (`setf` is completely absent). They allocate new nodes and
        share the unmodified subtrees (Structural Sharing), meaning
        previous versions of the table remain safely in memory. 

4.  **Lisp-2 Namespace Constraints:** Because Common Lisp has separate
        namespaces for variables and functions, variables that hold
        functions (like our continuations) *must* be invoked using
        `funcall`. I assumed the target audience understands this
        Lisp-2 quirk.

5.  **Fold Procedure Signature:** The prompt asked to make
      `table-fold` fully CPS. I assumed this meant the operation
       being applied over the fold (`proc`) must *also* be
       asynchronous/CPS capable. Therefore, `proc` does not return a
       value; it takes a fourth argument (`next-cont`) and must
       explicitly invoke it with the new accumulator. 
Prompt: Make these changes:
  • Nodes should be structs not lists.
  • Use docstrings to document the procedures, not comments.
  • Write these set operations on tables: union, intersection, and difference. Each of these operations should take two tables and return a new table that is the result of the operation. The original tables should be unchanged.
  Oh, now we're talking. Swapping lists for `defstruct` gives us actual type
safety and slightly faster access, and pushing the documentation into standard
Common Lisp docstrings makes it a truly idiomatic library.

Because we already built `table-fold` in pure
Continuation-Passing Style, we can use it to iterate over the tables to build
our sets asynchronously. We pass `#'identity` as the final continuation to
bridge the CPS world back into a direct return value for the final table.

  Here is the fully upgraded, struct-backed, structurally-shared Lisp
implementation.

  ### The Implementation (Common Lisp)

```lisp
;; =============================================================================
;; Struct Definition
;; =============================================================================

(defstruct (node (:constructor make-node (key val left right)))
  "A node in our immutable BST. Using a custom constructor for positional args."
  key val left right)

;; =============================================================================
;; CPS Table Abstraction (Immutable BST)
;; =============================================================================

(defun empty-table ()
  "Returns a new, empty table (nil)."
  nil)

(defun singleton-table (key value)
  "Returns a table initialized with a single key/value pair."
  (make-node key value nil nil))

(defun table-lookup (table key found-cont not-found-cont)
  "Looks up a KEY in the TABLE. 
   Calls FOUND-CONT with the value if found.
   Calls NOT-FOUND-CONT with no arguments if missing."
  (cond
    ((null table) 
     (funcall not-found-cont))
    ((= key (node-key table)) 
     (funcall found-cont (node-val table)))
    ((< key (node-key table)) 
     (table-lookup (node-left table) key found-cont not-found-cont))
    (t 
     (table-lookup (node-right table) key found-cont not-found-cont))))

(defun table-min (table found-cont not-found-cont)
  "Efficiently selects the least element (left-most node) in the table.
   Calls FOUND-CONT with (key value)."
  (cond
    ((null table) 
     (funcall not-found-cont))
    ((null (node-left table)) 
     (funcall found-cont (node-key table) (node-val table)))
    (t 
     (table-min (node-left table) found-cont not-found-cont))))

(defun table-insert (table key value)
  "Returns a NEW table with the key/value inserted. 
   O(log n) average time. Preserves strict immutability via structural sharing."
  (cond
    ((null table) 
     (singleton-table key value))
    ((= key (node-key table)) 
     (make-node key value (node-left table) (node-right table)))
    ((< key (node-key table)) 
     (make-node (node-key table) (node-val table)
                (table-insert (node-left table) key value)
                (node-right table)))
    (t 
     (make-node (node-key table) (node-val table)
                (node-left table)
                (table-insert (node-right table) key value)))))

(defun table-delete (table key)
  "Returns a NEW table with the specified key removed.
   Preserves strict immutability. Uses table-min for two-child deletion."
  (cond
    ((null table) nil)
    ((< key (node-key table))
     (make-node (node-key table) (node-val table)
                (table-delete (node-left table) key)
                (node-right table)))
    ((> key (node-key table))
     (make-node (node-key table) (node-val table)
                (node-left table)
                (table-delete (node-right table) key)))
    (t 
     (cond
       ((null (node-left table)) (node-right table))
       ((null (node-right table)) (node-left table))
       (t
        (table-min (node-right table)
                   (lambda (min-key min-val)
                     (make-node min-key min-val
                                (node-left table)
                                (table-delete (node-right table) min-key)))
                   (lambda () nil)))))))

(defun table-fold (table proc seed cont)
  "Iterates over the table from least to greatest key in pure CPS.
   PROC signature: (lambda (key value accumulator next-cont) ...)"
  (if (null table)
      (funcall cont seed)
      (table-fold (node-left table) proc seed
                  (lambda (left-acc)
                    (funcall proc (node-key table) (node-val table) left-acc
                             (lambda (current-acc)
                               (table-fold (node-right table) proc current-acc cont)))))))

;; =============================================================================
;; Functional Set Operations
;; =============================================================================

(defun table-union (t1 t2)
  "Returns a new table containing all key/value pairs from T1 and T2.
   If a key exists in both, the value from T2 takes precedence."
  (table-fold t2
              (lambda (k v acc next-cont)
                ;; Insert the t2 node into our accumulator (which starts as t1)
                (funcall next-cont (table-insert acc k v)))
              t1
              #'identity)) ; #'identity bridges CPS back to a direct return

(defun table-intersection (t1 t2)
  "Returns a new table containing only key/value pairs that exist in both T1 and T2.
   The value from T2 is kept."
  (table-fold t2
              (lambda (k v acc next-cont)
                (table-lookup t1 k
                              ;; Found in T1! Insert into our accumulator.
                              (lambda (val-t1)
                                (declare (ignore val-t1)) ; We use T2's value
                                (funcall next-cont (table-insert acc k v)))
                              ;; Not found in T1, skip it and pass acc unchanged.
                              (lambda ()
                                (funcall next-cont acc))))
              (empty-table)
              #'identity))

(defun table-difference (t1 t2)
  "Returns a new table containing all key/value pairs from T1 that do NOT exist in T2."
  (table-fold t2
              (lambda (k v acc next-cont)
                (declare (ignore v))
                ;; Delete T2's key from our accumulator (which starts as T1)
                (funcall next-cont (table-delete acc k)))
              t1
              #'identity))
```

  ### Usage Examples & Tests (Common Lisp)

  Here are the tests proving the struct logic holds up and that our new set
operations successfully bridge the CPS fold back into standard functional
returns.

```lisp
;; =============================================================================
;; Tests and Usage Examples
;; =============================================================================

(format t "--- Running CPS Table Tests (Structs & Sets) ---~%")

;; Setup two tables for our set operations
(defparameter *table-a* 
  (table-insert (table-insert (table-insert (empty-table) 1 'A) 2 'B) 3 'C))
  
(defparameter *table-b* 
  (table-insert (table-insert (table-insert (empty-table) 3 'C-NEW) 4 'D) 5 'E))

;; 1. Test Union
(defparameter *union-tab* (table-union *table-a* *table-b*))
(format t "Test 1: Union (Should have 1, 2, 3, 4, 5. Key 3 should be 'C-NEW) ->~%")
(table-fold *union-tab*
            (lambda (k v acc next)
              (format t "  Key: ~a, Val: ~a~%" k v)
              (funcall next t))
            nil #'identity)

;; 2. Test Intersection
(defparameter *inter-tab* (table-intersection *table-a* *table-b*))
(format t "Test 2: Intersection (Should only have 3: 'C-NEW) ->~%")
(table-fold *inter-tab*
            (lambda (k v acc next)
              (format t "  Key: ~a, Val: ~a~%" k v)
              (funcall next t))
            nil #'identity)

;; 3. Test Difference
(defparameter *diff-tab* (table-difference *table-a* *table-b*))
(format t "Test 3: Difference (A - B) (Should have 1, 2) ->~%")
(table-fold *diff-tab*
            (lambda (k v acc next)
              (format t "  Key: ~a, Val: ~a~%" k v)
              (funcall next t))
            nil #'identity)
            
;; 4. Verify Immutability
(format t "Test 4: Verify Immutability of Original Tables ->~%")
(table-lookup *table-a* 4
              (lambda (v) (format t "FAIL: *table-a* was mutated!~%"))
              (lambda () (format t "PASS: *table-a* is untouched.~%")))
```

  ### Assumptions Made for this Upgrade:

1. **Conflict Resolution in Sets:** When performing `union` or
    `intersection` on tables with colliding keys, a decision has to be
    made on whose value wins. I built it so the second argument (`t2`)
    always overwrites `t1`. 

2. **Identity Continuation (`#'identity`):** Since `table-fold` is
    strictly CPS and takes a final continuation, I used Common Lisp's
    built-in `#'identity` function as the final bridge. This means
    when the fold completes its asynchronous-style loop, it passes the
    final accumulated table to `identity`, which just spits it right
    back out as a synchronous return value. 

3. **Struct Accessors:** By using `(defstruct (node ...))`, Lisp
    automatically generates `node-key`, `node-val`, `node-left`, and
    `node-right`. This matched the helper functions I built in the
    previous iteration perfectly, so the core BST logic didn't need to
    be rewritten, just optimized under the hood. 
Prompt: Write a table-lookup* procedure which takes a list of keys. The outermost table is assumed to be a table of tables. The first key is looked up in the outermost table to yield an inner table. This process is repeated for each key in the list yeilding the final value from the innermost table. If any key is not found, the not-found continuation is called. If all keys are found, the found continuation is called with the final value.
  Oh, man. This is where Continuation-Passing Style goes from "neat academic
trick" to "absolute superpower."

  If you were writing a deep nested lookup in standard imperative style, you'd
be dealing with a messy stack of `if/else` checks at every level to see if a key
returned a null value before proceeding to the next. But in CPS? We just chain
the success continuations and pass the *exact same* failure continuation down
the line. If it hits a dead end at level 10, it instantly bails out using the
original `not-found-cont` without having to manually unspool a call stack of
errors.

  ### The Implementation (Common Lisp)

```lisp
(defun table-lookup* (table keys found-cont not-found-cont)
  "Traverses a nested table structure using a list of KEYS.
   If all keys are found sequentially, calls FOUND-CONT with the innermost value.
   If any key is missing along the path, instantly calls NOT-FOUND-CONT."
  (if (null keys)
      ;; Base case: we've exhausted the keys. 
      ;; Whatever we are currently holding is the final target.
      (funcall found-cont table)
      
      ;; Recursive step: look up the first key in the current table.
      (table-lookup table (first keys)
                    ;; If found, the value becomes the 'table' for the next step.
                    ;; We recursively call table-lookup* with the rest of the keys.
                    (lambda (next-level-table)
                      (table-lookup* next-level-table 
                                     (rest keys) 
                                     found-cont 
                                     not-found-cont))
                    ;; If NOT found at any level, just fire the failure continuation.
                    not-found-cont)))
```

  ### Usage Examples & Tests

  Let's build a nested table structure (a table, inside a table, inside a table)
and test it out.

```lisp
;; =============================================================================
;; Tests for Nested Lookup (table-lookup*)
;; =============================================================================

(format t "--- Running CPS Nested Lookup Tests ---~%")

;; 1. Build the nested tables
;; innermost: { 'z : 'target-acquired }
(defparameter *inner-table* 
  (singleton-table 'z 'target-acquired))

;; middle: { 'y : *inner-table* }
(defparameter *middle-table* 
  (singleton-table 'y *inner-table*))

;; outer: { 'x : *middle-table*, 'a : 'dummy-value }
(defparameter *outer-table* 
  (table-insert (singleton-table 'x *middle-table*) 'a 'dummy-value))

;; 2. Test Success Path
(format t "Test 1: Deep lookup for path (x y z) -> ")
(table-lookup* *outer-table* '(x y z)
               (lambda (val) (format t "FOUND: ~a~%" val))
               (lambda () (format t "NOT FOUND~%")))
;; Expected: FOUND: TARGET-ACQUIRED

;; 3. Test Partial Failure (breaks at level 2)
(format t "Test 2: Deep lookup for missing path (x BAD-KEY z) -> ")
(table-lookup* *outer-table* '(x BAD-KEY z)
               (lambda (val) (format t "FAIL: Should not have found ~a~%" val))
               (lambda () (format t "NOT FOUND (As expected)~%")))
;; Expected: NOT FOUND (As expected)

;; 4. Test Zero Keys (Edge Case)
(format t "Test 3: Deep lookup with empty key list -> ")
(table-lookup* *outer-table* '()
               (lambda (val) (format t "FOUND: ~a~%" (type-of val)))
               (lambda () (format t "NOT FOUND~%")))
;; Expected: FOUND: CONS (Returns the outer table struct itself)
```

  ### Assumptions Made for this Procedure:

  Here's the context for the blog post:

1. **Dynamic Typing is our Friend:** I assumed the system can
  dynamically handle the transition from "Table Struct" to "Final
  Value". Notice how when the key list is empty `(null keys)`, it just
  returns whatever `table` is currently holding. Because Lisp is
  dynamically typed, `table` in the final recursive step isn't
  actually a table struct anymore—it's the final primitive value (like
  the symbol `'target-acquired`). We didn't have to write complex
  type-checking or casting; the CPS flow just hands it over. 

2. **Empty Key List Behavior:** I assumed that if the user passes an
  empty list of keys `()`, they want whatever object was passed as the
  `table` argument returned to them via `found-cont`. This is the
  mathematically pure base-case for traversing a path of length zero. 

3. **Homogeneous Continuations:** I assumed `not-found-cont` doesn't
  need to know *where* it failed (e.g., it doesn't need to know it
  failed on key `y`). It just triggers a catastrophic bailout. If they
  wanted a trace, we could have modified `not-found-cont` to accept
  the failing key, but that violates the established `table-lookup`
  signature.  

--- Running CPS Nested Lookup Tests ---
; Debugger entered on #<TYPE-ERROR expected-type: NUMBER datum: >

 Dammit, I'm an idiot. I tripped over my own explicitly
stated assumption.

  Remember in the BST upgrade when I said: *"Because we are building a BST... I
assumed the keys are real numbers and used Common Lisp's numerical comparators
(`<`, `>`, `=`)."*?

  Well, I got so caught up in how beautiful the `table-lookup*` CPS logic was
that I built the test cases for it using symbols (`'x`, `'y`, `'a`) instead of
numbers. When `table-insert` tried to build `*outer-table*`, it tried to
evaluate `(< 'a 'x)` and Common Lisp rightly slapped us with a type error.

  The `table-lookup*` procedure itself is flawless. The bug is entirely in my
test data.

  Here are the corrected tests using integers for keys so the BST comparison
operators actually work.

```lisp
;; =============================================================================
;; CORRECTED Tests for Nested Lookup (table-lookup*)
;; =============================================================================

(format t "--- Running CPS Nested Lookup Tests ---~%")

;; 1. Build the nested tables using NUMBERS for keys
;; innermost: { 300 : 'target-acquired }
(defparameter *inner-table* 
  (singleton-table 300 'target-acquired))

;; middle: { 200 : *inner-table* }
(defparameter *middle-table* 
  (singleton-table 200 *inner-table*))

;; outer: { 100 : *middle-table*, 50 : 'dummy-value }
;; (Inserting 50 to prove the BST routing still works)
(defparameter *outer-table* 
  (table-insert (singleton-table 100 *middle-table*) 50 'dummy-value))

;; 2. Test Success Path
(format t "Test 1: Deep lookup for path (100 200 300) -> ")
(table-lookup* *outer-table* '(100 200 300)
               (lambda (val) (format t "FOUND: ~a~%" val))
               (lambda () (format t "NOT FOUND~%")))
;; Expected: FOUND: TARGET-ACQUIRED

;; 3. Test Partial Failure (breaks at level 2)
(format t "Test 2: Deep lookup for missing path (100 999 300) -> ")
(table-lookup* *outer-table* '(100 999 300)
               (lambda (val) (format t "FAIL: Should not have found ~a~%" val))
               (lambda () (format t "NOT FOUND (As expected)~%")))
;; Expected: NOT FOUND (As expected)

;; 4. Test Zero Keys (Edge Case)
(format t "Test 3: Deep lookup with empty key list -> ")
(table-lookup* *outer-table* '()
               (lambda (val) (format t "FOUND: ~a~%" (type-of val)))
               (lambda () (format t "NOT FOUND~%")))
;; Expected: FOUND: NODE (Returns the outer table struct itself)

What began as a straightforward exercise in generating a Continuation-Passing Style (CPS) table abstraction quickly evolved into a demonstration of complex architectural synthesis. Moving from a linear list in Scheme to an immutable Binary Search Tree in Common Lisp requires the model to seamlessly integrate multiple paradigms: strict functional immutability, structural sharing, Lisp-2 namespace constraints, and pure asynchronous control flow via CPS.

The implementation of table-fold and the subsequent set operations (union, intersection, and difference) highlight an understanding of how continuations can be leveraged to abstract iteration. Furthermore, the table-lookup* procedure demonstrates the practical power of CPS—short-circuiting deep recursive traversals upon failure without the need for exception handling or manual stack unrolling.

However, the session also underscores the reality of LLM-assisted programming: the model is a powerful synthesizer, but it is not infallible. As evidenced by the `TYPE-ERROR` during the testing phase of the nested lookup, the model can architect abstract logic while simultaneously tripping over its own implicit assumptions regarding concrete test data (in this case, feeding symbols into a numeric comparator).

The LLM is not writing perfect software in a vacuum. But the LLM is capable of writing, refactoring, and debugging complex computer science constructs, like pure CPS in Common Lisp, provided there is a human engineer in the loop to define the constraints, run the REPL, and steer the architecture. It appears that the model is not merely regurgitating syntax, but actively applying functional programming concepts to novel problems.

Joe Marshall — The Functional Refactoring Pass

· 96 days ago

This is an anecdote, not a data point, yet.

I'm a firm believer in functional programming and I consider myself a `mostly functional` programmer. I use functional programming when I can, but when a side effect is required, I'll use it. I'm not a purist.

Functional programming is supposed to have a number of advantages over imperative, procedural programming. The primary advantage is that there are provably no race conditions. You can trivially scale functional code to multiple threads and multiple processors. In theory, functional code is easier to reason about and easier to test because each function can be reasoned about and tested in isolation. In practice, functional code can become a maze of thunks and lambdas that many find difficult to read. Nonetheless, I prefer to reason about tangled lambdas than to reason about tangled state.

I believe that functional code is easier for an LLM to reason about as well. I haven't proven this, but anecdotally it seems to be the case. In theory, the LLM would gain all the usual benefits of functional programming. It would find the code easier to reason about and easier to test.

Unfortunately, the vast majority of code that the LLM has been trained on is imperative, procedural code. The LLM can write functional code when specifically prompted, but it will default to writing imperative, procedural code.

If you start a vibe coding project ab initio, you'll get a lot of imperative, procedural code, and the LLM will have more and more difficulty reasoning about it as the project grows. To stop this from happening, I prompt the LLM to refactor the code to be more functional. I do this fairly early on in the project, once the project starts to show signs of life.

The functional refactoring is a multi-step process and the best way to do it is to prompt the LLM to first create a plan for the refactoring. I use a prompt something like this:

Make a plan. We need the code to be refactored to be more functional and to adhere to functional programming principles. Take several steps to refactor the code so that the main interaction path is functional and stateless. Move the side effects to the edges of the codebase. Use functional programming techniques such as monads and reactive programming to keep the core of the codebase functional. Make sure that utility functions are pure and stateless. Write the plan to a file FUNCTIONAL_REFACTORING.md

The LLM will cogitate for a while and will write a multi-step plan for the refactoring. Here is the plan that the LLM generated for the jrm-code-project.com web site.

# Functional Refactor Plan for `jrm-code-project`

**Author's lens:** Senior Functional Programming Architect
**Scope:** `package.lisp`, `csrf.lisp`, `server.lisp`, `auth.lisp`, `billing.lisp`,
`admin.lisp`, `chef.lisp`, `db-auth.lisp`, `stripe.lisp`, `jwt.lisp`, `totp.lisp`, `ses.lisp`
**Status:** Complete. Phases 1-8 below have all landed as separate,
individually-tested commits; the codebase now reflects this plan. The
phase write-ups are retained as historical design-rationale documentation
-- comments elsewhere in the codebase that cite "FUNCTIONAL_REFACTOR.md
Phase N" are pointing at finished work, not an in-progress migration.

---

## 0. Framing

This codebase is a working, well-organized Hunchentoot application (the recent
file split into `csrf`/`server`/`auth`/`billing`/`admin`/`chef` was a good move
along the *separation-of-concerns* axis). But every one of those modules is
written in a straight-line, **imperative-shell-with-no-functional-core** style:
HTTP handling, session mutation, SQL, third-party HTTP calls, HTML rendering,
and business rules are all fused into single `DEFUN`s that read the world,
mutate the world, and print strings, in one undifferentiated breath.

The project already imports `SERIES`, `FOLD`, `FUNCTION` (compose/inverse), and
`NAMED-LET` — real functional-programming firepower — via shadowing imports in
`package.lisp`. Almost none of it is actually used in the handler code; the
shadowed `LET`/`DEFUN`/`LET*`/`MULTIPLE-VALUE-BIND` forms are used as drop-in
replacements for their vanilla CL counterparts, not as a foundation for a
different *style* of programming. That's the central irony this plan
addresses: the tools for a functional architecture are already a dependency of
the system; they're just not driving any design decisions yet.

The plan below does **not** propose rewriting Hunchentoot, Postmodern, or
Stripe's HTTP API into something pure — those are unavoidably effectful
boundaries. It proposes pushing effects to the *edges* (a thin imperative
shell) and pulling everything else — validation, view-model construction,
tier/authorization logic, Stripe payload shaping, HTML rendering — into a
**pure, immutable, composable core** that can be unit-tested without a
database, without Hunchentoot, and without live Stripe credentials.

---

## 1. Anti-Pattern Catalog (current state)

### 1.1 Global mutable state used as an implicit parameter-passing channel

- `*acceptor*` (`server.lisp`) — mutated by `start-server`/`stop-server`.
- `*stripe-tier-price-ids*`, `*stripe-tier-product-ids*`, `*stripe-price-id-tiers*`,
  `*stripe-billing-portal-configuration-id*` (`stripe.lisp`) — four separate
  `DEFVAR`s, populated by side-effecting `PUSH` inside `ensure-tier-product`
  and `ensure-billing-portal-configuration`, and read by unrelated functions
  (`tier-price-id`, `tier-from-price-id`, `create-billing-portal-session`)
  scattered throughout the file. This is really *one* piece of "Stripe
  catalog" data, represented as four uncoordinated globals that must be
  mutated in lock-step (see `init-stripe-product`, which zeroes all four by
  hand before repopulating them) — a classic sign that a single immutable
  value is trying to escape.
- Every handler reaches into `hunchentoot:session-value`/`hunchentoot:cookie-in`
  as ambient dynamic state rather than being handed an explicit `Request`
  value. E.g. `dashboard-page` (`auth.lisp`) pulls `:authenticated-user` from
  the session, `challenge-2fa-page` reads/writes `:limbo-email` and
  `:post-login-redirect` via `setf` in the middle of a rendering branch.

### 1.2 God-functions that fuse I/O, business logic, and presentation

Nearly every `hunchentoot:define-easy-handler` in `auth.lisp`, `billing.lisp`,
and `admin.lisp` does all of the following in one function body:

1. Read ambient state (session, cookies, POST params).
2. Validate/branch on it.
3. Call the database or an external HTTP API (side effect #1).
4. Mutate session/cookie state (side effect #2).
5. Build and return an HTML string via nested `FORMAT` calls (presentation).

`dashboard-page` (`auth.lisp`) is the extreme case: ~250 lines mixing tier
math, JWT issuance (a side effect), a conditional redirect, and a giant
`FORMAT` template with 20+ interpolation arguments computed inline. There is
no way to unit-test "what should the dashboard tier grid look like for a
LAMBDA-tier user with a Stripe customer ID" without spinning up Hunchentoot,
a session, and a database row.

`stripe-webhook-handler` (`billing.lisp`) mixes signature verification,
JSON parsing, event-type dispatch, and five different DB-mutation call sites
in one `COND`, with logging `FORMAT` calls interleaved — untestable without a
live (or heavily mocked) Postgres connection and a hand-built JSON fixture.

### 1.3 Stringly-typed, un-composable HTML rendering

Every page is a hand-written `FORMAT nil "<html>...~A...</html>"` template.
Consequences:

- No composition: the "vault" card, the "tier grid", and the notification
  banner in `dashboard-page` cannot be reused or tested independently — they
  are inline slices of one giant format string.
- No enforced escaping discipline: some interpolations go through
  `hunchentoot:escape-for-html` (e.g. `(hunchentoot:escape-for-html user)`),
  others don't (e.g. tier-derived CSS class strings, which happen to be safe
  today only because they come from a fixed internal vocabulary) — the
  safety property is not structurally guaranteed, only true by convention and
  developer discipline.
- Every handler re-embeds the same `<style>` block or repeats layout
  boilerplate (`signup-page` and `setup-2fa-page` both hand-roll near-identical
  `<html><head><style>...` wrappers).

### 1.4 Alist-of-keywords as a poor man's record type

`db-auth.lisp`'s `get-user`/`list-users`/`get-user-by-customer` all return
`postmodern:query ... :alists` rows, and every caller repeats
`(cdr (assoc :membership-tier user-data))`, `(cdr (assoc :wheel user-data))`,
etc. — by grep, this exact shape appears **20+ times** across `auth.lisp`,
`billing.lisp`, and `admin.lisp`. There is no `USER` type: the "schema" is an
implicit contract enforced only by every call site independently getting the
keyword spelling right (`:stripe-subscription-id` vs. a typo would fail
silently, returning `NIL`, not a compile- or run-time error).

### 1.5 Side-effecting, non-monadic error/control flow

- `csrf.lisp`'s `WITH-CSRF-PROTECTION` macro is a control-flow combinator
  wearing a syntactic disguise: it's really "if failure, mutate the HTTP
  return code and short-circuit" — imperative branching hidden inside a
  `DEFMACRO`, not a composable value.
- `jwt.lisp`'s `require-membership-tier`/`require-wheel`/`require-membership-jwt`
  each *either* return a value *or* perform a side-effecting `REDIRECT` and
  return `NIL` — callers are contractually obligated to check for `NIL` and
  "immediately stop processing" (a convention documented in a comment,
  not enforced by the type/control-flow system). This is exactly the shape
  `Either`/`Result`/`Maybe` monadic short-circuiting exists to replace.
  Compare with e.g. `require-session-wheel` in `admin.lisp`, which duplicates
  the same "return value or redirect-and-return-nil" shape independently for
  session-based (not JWT-based) authorization — the same *pattern* implemented
  twice, un-abstracted.
- `stripe-webhook-handler` and `roast-code-with-gemini`/`chef-handler` use
  `HANDLER-CASE` around large blocks and communicate failure by mutating
  `hunchentoot:return-code*` and returning an ad hoc string — errors are
  effectively `(values nil side-effect)`, not typed outcomes.

### 1.6 Duplicated imperative HTTP-client boilerplate

`stripe.lisp` rebuilds `(stripe-auth-headers secret-key)` and re-checks
`(and secret-key (not (string= secret-key "")))` in nearly every function
(`find-existing-tier-product`, `create-tier-product`,
`ensure-billing-portal-configuration`, `create-stripe-checkout-session`,
`create-billing-portal-session`, `get-stripe-subscription-tier`,
`cancel-stripe-subscription-with-prorated-refund`) — eight independent,
hand-written guard clauses for what is structurally one precondition
("do we have Stripe configured") and one authenticated-GET/POST helper.
Request payloads are built as raw `(cons "key[bracket][path]" "value")` lists
by hand at each call site (see the billing-portal-configuration content-list
construction) rather than through a small combinator/DSL that could be unit
tested for correct shape independent of the network call.

### 1.7 Unused functional idioms already in scope

`package.lisp` imports `SERIES` (lazy, compiler-fused sequence pipelines) and
`FOLD`, yet the codebase's list processing — `list-users` pagination,
`mapcar #'render-member-row members`, `dolist` loops in `db-auth.lisp` and
`stripe.lisp`, the `LOOP ... COLLECT` in `generate-recovery-codes` — is all
plain `CL:LOOP`/`DOLIST`/`MAPCAR` with `SETF`-based accumulation
(`random-string`'s `(setf (char res i) ...)` loop, `admin-members-page`'s
imperative pagination math). None of it is wrong CL, but it means the
project's own stated architectural direction (series/fold-based composition)
isn't actually load-bearing anywhere yet.

### 1.8 Testing is coupled to live, mutable external state

`recovery-code-verification`, `stripe-database-and-routes`, and
`user-membership-tiers` (per `tests/tests.lisp` and this repo's own
documented conventions) require a live Postgres instance and mutate real
rows. This is a direct consequence of §1.2/§1.4: because business logic is
never separated from the DB/HTTP shell, there is no way to test "does
`tier-meets-minimum-p` correctly rank CADR above CONS" or "does the webhook
handler correctly map a `customer.subscription.deleted` event to a
cancellation" without a database in the loop.

---

## 2. Target Architecture

**Functional core, imperative shell**, applied consistently:

```
┌─────────────────────────────────────────────────────────────┐
│ Imperative shell (thin, at the edges only)                   │
│  - Hunchentoot handlers: parse Request, call pure core,      │
│    interpret its pure Response/Effect value, perform I/O.    │
│  - Postmodern calls: translate SQL rows <-> immutable domain │
│    records at the boundary only.                             │
│  - Stripe/Gemini HTTP calls: translate typed request records │
│    <-> typed response records at the boundary only.          │
│  - *ACCEPTOR*, *STRIPE-CATALOG*, cookie/session get/set.      │
└───────────────────────────┬───────────────────────────────────┘
                            │ immutable values only cross this line
┌───────────────────────────▼───────────────────────────────────┐
│ Pure functional core (the bulk of new/moved code)             │
│  - Domain records: USER, MEMBERSHIP-CLAIMS, STRIPE-CATALOG,   │
│    CHECKOUT-REQUEST, WEBHOOK-EVENT, VIEW-MODEL, RESULT.       │
│  - Pure decision functions: tier-meets-minimum-p,              │
│    dashboard-view-model, webhook-event->db-commands,          │
│    checkout-request->stripe-params, csrf-check, auth-check.   │
│  - Pure rendering functions: view-model -> HTML string.       │
│  - Composable middleware combinators over a Request->Result   │
│    handler shape.                                              │
└─────────────────────────────────────────────────────────────────┘
```

Key design commitments:

1. **Immutable domain records, not alists-of-keywords.** Every "row" that
   crosses the DB boundary becomes a `defstruct` (or `defclass` with
   `:read-only` when the CLOS overhead-per-instance is not a concern) with
   named, typed accessors — `user-membership-tier`, `user-wheel-p`, etc. —
   constructed once at the DB boundary via a single `row->user` converter,
   never re-derived by ad hoc `(cdr (assoc :x row))` at call sites.

2. **Explicit `Result`/`Either`-style outcomes instead of "return NIL and
   trust the caller to have already redirected."** A tiny `defstruct result`
   (or reuse of `(values status payload)`, or a proper condition-based
   approach — see Phase 6) makes success/failure a first-class value that
   the *shell* interprets (issue a redirect, render an error page), rather
   than a side effect the *core* performs mid-computation.

3. **Middleware as composable functions, not macros with inline control
   flow.** `WITH-CSRF-PROTECTION`, `require-membership-tier`,
   `require-session-wheel` all collapse into one combinator shape:
   `(defun wrap-with-csrf (handler) ...)`, `(defun wrap-with-tier (min-tier handler) ...)`,
   composed via `FUNCTION:COMPOSE` (already a dependency!) at route-definition
   time, e.g. `(compose (require-tier "CADR") require-login csrf-protected) #'chef-page-core)`.

4. **Pure view-model construction, separated from HTML string rendering,
   separated from the HTTP handler.** `dashboard-page` becomes: (a) a pure
   `dashboard-view-model` function (user record + query params -> an
   immutable `DASHBOARD-VIEW-MODEL` struct), (b) a pure `render-dashboard`
   function (view-model -> HTML string, independently unit-testable with
   hand-built view-models and no session/DB at all), and (c) a thin handler
   that wires the two together and performs the one real side effect
   (issuing the JWT cookie).

5. **One immutable `Stripe` catalog value, not four mutable globals.**
   `ensure-tier-product`/`ensure-billing-portal-configuration` become pure
   functions that *return* an updated `STRIPE-CATALOG` record; `init-stripe-product`
   becomes the one place that takes the pure result and stores it in a single
   `*stripe-catalog*` global (still a necessary impurity — Stripe's actual
   product IDs are genuinely mutable external state fetched once at startup —
   but now it's *one* clearly-labeled impurity instead of four unsynchronized
   ones).

6. **Lean on `SERIES`/`FOLD` where they fit naturally** (pagination,
   filtering, tier-ranking, recovery-code generation) so the project's own
   declared functional dependencies start pulling their weight, without
   forcing awkward `SERIES` usage onto genuinely imperative I/O loops (the
   SMTP hand-rolled protocol in `ses.lisp`, for instance, is legitimately
   sequential/stateful and is *not* a refactor target for series-ification).

---

## 3. Non-Goals

- **Not** rewriting Hunchentoot request handling, Postmodern's connection
  model, or the raw SMTP-over-TLS code in `ses.lisp` — these are genuine
  imperative shells (sockets, connections, OS processes) and should stay
  imperative, just kept as thin and as clearly bounded as possible.
- **Not** introducing a heavyweight external templating engine or ORM as a
  prerequisite — the plan below builds small in-house combinators sized to
  this codebase, consistent with its existing dependency footprint
  (`alexandria`, `fold`, `function`, `series`).
- **Not** a big-bang rewrite. Every phase below ships independently, keeps
  `(asdf:test-system :jrm-code-project)` green throughout, and preserves
  every documented behavior (CSRF exemptions, the `next` breadcrumb, JWT
  redirect-to-`/` semantics, wheel bootstrap, etc.) verbatim.

---

## 4. Incremental Migration Plan

Each phase is scoped to be its own PR/commit, independently testable, and
reversible. Phases are ordered so that later phases can build on the domain
types and combinators introduced earlier ones.

### Phase 1 — Immutable domain records at the database boundary
**Files touched:** `db-auth.lisp`, call sites in `auth.lisp`, `billing.lisp`,
`admin.lisp`.

- Introduce `defstruct (user (:copier nil))` (email, password-hash,
  totp-secret, auth-state, stripe-customer-id, stripe-subscription-id,
  subscription-status, membership-tier, wheel-p) plus a single
  `row->user` converter used by `get-user`, `get-user-by-customer`, and
  `list-users`.
- `get-user`, `list-users`, etc. keep their existing names/call signatures
  (no handler changes yet) but return `USER` structs instead of alists.
- Replace every `(cdr (assoc :membership-tier user-data))`-style call site
  with `(user-membership-tier user-data)`.
- **Payoff:** typos become compile-time `SLOT-UNBOUND`/undefined-function
  errors instead of silent `NIL`; this is the least risky phase (pure
  mechanical substitution) and unblocks everything else.
- **Tests:** existing FiveAM DB tests continue to pass unchanged (they
  already exercise these accessors indirectly); add direct unit tests for
  `row->user` using a hand-built alist fixture, no DB required.

### Phase 2 — Extract pure decision logic out of handlers
**Files touched:** new `tier.lisp` (or fold into `jwt.lisp`), `auth.lisp`,
`billing.lisp`.

- Move `tier-rank`/`tier-meets-minimum-p` (already pure!) into a dedicated,
  independently-tested module — they're the easiest possible first win.
- Extract the *decision* half of `dashboard-page` into a pure
  `dashboard-view-model` function: given a `USER`, a `checkout-status`, and a
  `next` param, return an immutable `DASHBOARD-VIEW-MODEL` struct (tier
  flags, badge/button HTML fragments *as data*, e.g.
  `(:active-p t :badge :current :button :manage-subscription)` rather than
  pre-rendered HTML — defer string rendering to Phase 5).
- Extract the *decision* half of `stripe-webhook-handler`'s event dispatch
  into a pure `webhook-event->db-commands` function: given the decoded JSON
  alist, return a list of *data* describing what should happen (e.g.
  `(:update-subscription :email ... :tier ...)`), with a thin imperative
  loop in the handler that executes each command against `jrm-auth:*`.
- **Payoff:** these pure functions get direct FiveAM unit tests with
  hand-built fixtures — no Postgres, no Hunchentoot, no live Stripe webhook
  payloads needed to verify "a `customer.subscription.deleted` event
  produces a cancel command for the right user."

### Phase 3 — Composable middleware combinators
**Files touched:** `csrf.lisp`, `jwt.lisp`, `admin.lisp`.

- Replace `WITH-CSRF-PROTECTION` (macro) with a higher-order function
  `wrap-csrf-protected` that takes a zero-argument thunk (or, once Phase 4
  handler shape lands, a `Request -> Result` handler) and returns a value
  representing either "proceed" or "403 forbidden" — usable both as today's
  macro (thin `defmacro with-csrf-protection (&body body) `(funcall
  (wrap-csrf-protected (lambda () ,@body)))`, preserving all call sites) *and*
  directly composable with `FUNCTION:COMPOSE` for new code.
- Unify `require-membership-tier`, `require-wheel`, and `admin.lisp`'s
  hand-rolled `require-session-wheel` behind one combinator shape:
  `(defun require (predicate on-failure) ...)`, parameterized by *what* to
  check (JWT tier, session wheel bit) and *what to do on failure*
  (redirect-to-login vs. redirect-to-dashboard vs. redirect-to-upgrade),
  eliminating the duplicated "return value or side-effecting-redirect-and-nil"
  pattern called out in §1.5.
- **Payoff:** one audited implementation of "check X, else redirect Y" instead
  of three ad hoc ones; new protected routes become one line of composition
  instead of copy-pasted boilerplate.

### Phase 4 — Consolidate Stripe catalog state into one immutable value
**Files touched:** `stripe.lisp`.

- Introduce `(defstruct stripe-catalog tier-price-ids tier-product-ids
  price-id-tiers billing-portal-configuration-id)`.
- Rewrite `ensure-tier-product`, `ensure-billing-portal-configuration`, and
  `init-stripe-product` as pure functions of `(catalog, ...) -> new-catalog`
  (the actual Stripe HTTP calls remain side effects, but the *bookkeeping*
  that today happens via four `PUSH`es across two functions becomes one
  `(defun catalog-with-tier (catalog tier price-id product-id) ...)`
  returning a fresh struct).
- `*stripe-tier-price-ids*` etc. collapse into a single `*stripe-catalog*`
  global, set once by `init-stripe-product`, read via small accessor
  functions (`tier-price-id`, `tier-from-price-id`) that close over it —
  same call-site API, one source of truth underneath.
- Extract the repeated `(and secret-key (not (string= secret-key "")))`
  guard and `stripe-auth-headers` construction into a single
  `with-stripe-credentials (headers) ...` macro/combinator so the eight
  duplicated guard clauses in §1.6 collapse to one.
- **Payoff:** `init-stripe-product`'s "zero all four, then repopulate" dance
  disappears; the catalog can never be observed half-updated.

### Phase 5 — Pure, composable HTML rendering
**Files touched:** new `views.lisp`, `auth.lisp`, `billing.lisp`, `admin.lisp`.

- Introduce small rendering combinators: `(html-page title body-html)`,
  `(html-form action fields &key csrf-token)`, `(html-notification kind text)`
  — pure string -> string functions, each independently testable.
- Rewrite the Phase-2 `DASHBOARD-VIEW-MODEL` -> HTML as a pure
  `render-dashboard` function built from the above combinators; the
  `dashboard-page` handler shrinks to "build view-model, issue JWT cookie,
  call `render-dashboard`."
- Apply the same pattern to `admin-members-page`/`render-member-row` (already
  half-decomposed — `render-member-row` is already a pure function of a
  `USER`; formalize it as `(user -> html)` operating on the Phase-1 struct)
  and to the repeated signup/2FA/login page chrome.
- Standardize escaping: every interpolated *user-controlled* value flows
  through one `(html-escape value)` combinator used *inside* the rendering
  combinators themselves, so escaping is structurally guaranteed rather than
  convention-dependent (closes the gap in §1.3).
- **Payoff:** view logic becomes unit-testable ("does a LAMBDA-tier user
  with no Stripe customer ID render a disabled CONS button and an active
  LAMBDA badge?") without any I/O; duplicated page chrome collapses to one
  `html-page` call per handler.

### Phase 6 — Explicit outcome values for error handling
**Files touched:** `billing.lisp` (webhook + checkout), `chef.lisp` (Gemini
call), `stripe.lisp`.

- Introduce a minimal `(defstruct (result (:constructor ok (value)))
  value)` / `(defstruct (failure (:constructor err (reason))) reason)` pair
  (or a tagged `(cons :ok value)` / `(cons :error reason)` if a full struct
  is overkill) used by `roast-code-with-gemini`, `create-stripe-checkout-session`,
  and the webhook command interpreter from Phase 2.
- Handlers interpret the `RESULT`/`FAILURE` value at the shell boundary
  (mutate `return-code*`, pick the right error string) — the pure/impure
  split becomes: *pure code computes an outcome value; only the handler
  performs the HTTP-visible side effect of reporting it.*
- **Payoff:** `stripe-webhook-handler`'s `HANDLER-CASE`-wrapped cascade of
  five DB mutations becomes: compute a list of typed commands (Phase 2),
  execute them, collect any resulting `FAILURE`s, report once — testable end
  to end by mocking the command-execution step.

### Phase 7 — Lean on `SERIES`/`FOLD` for sequence-shaped logic
**Files touched:** `db-auth.lisp`, `admin.lisp`, `stripe.lisp`.

- `admin-members-page`'s pagination math (`offset`, `total-pages`,
  `has-prev`/`has-next`) and `random-string`'s character-by-character
  `SETF` loop are natural, low-risk candidates for `SERIES`-based rewrites
  once the surrounding data is already immutable (Phases 1 and 5).
- `generate-recovery-codes`'s `LOOP REPEAT 10 COLLECT ...` and the
  `dolist`-based Stripe tier-plan initialization in `init-stripe-product`
  are good `FOLD`/`SERIES` candidates once Phase 4 makes the underlying
  state immutable.
- Treat this phase as *opportunistic polish*, not a hard requirement — the
  goal is internal consistency with the project's declared dependencies, not
  a mandate to force every loop into `SERIES` syntax.

### Phase 8 — Test suite rebalancing
**Files touched:** `tests/tests.lisp`.

- Once Phases 1-6 land, add a large batch of **pure unit tests** requiring no
  Postgres/Stripe/Hunchentoot: `row->user`, `tier-meets-minimum-p`,
  `dashboard-view-model`, `webhook-event->db-commands`, `render-dashboard`,
  `catalog-with-tier`, the CSRF/tier middleware combinators.
- Keep the existing live-Postgres tests (`recovery-code-verification`,
  `stripe-database-and-routes`, `user-membership-tiers`) as the *thin*
  integration-test layer that only needs to verify the imperative shell
  correctly wires pure functions to real I/O — their scope should shrink
  over time as more logic moves into directly-tested pure functions.
- **Payoff:** CI/local runs that don't have Postgres available can still
  exercise the majority of the codebase's actual logic; the live-DB tests
  become a smaller, more focused confirmation layer instead of the primary
  way anything gets tested.

---

## 5. Sequencing & Risk Notes

- Phases are ordered by **increasing dependency on prior phases**, not by
  file. Do not skip Phase 1 — every later phase assumes `USER` (and later
  `STRIPE-CATALOG`) structs exist, so alist-accessor call sites should be
  fully migrated before Phase 2 work begins on the same files.
- Each phase should land as its own commit/PR with `(asdf:test-system
  :jrm-code-project)` green before and after — this plan is explicitly
  incremental so the app is deployable after every single phase.
- No phase changes an HTTP-visible behavior (routes, redirects, cookie
  names/lifetimes, CSRF exemption list, the `next` breadcrumb contract, or
  JWT-missing-redirects-to-`/` semantics) — those are refactors of
  *implementation*, not of *behavior*. Any phase whose diff would change
  observable behavior should be split so the behavior change is its own,
  separately-reviewed commit.
- `ses.lisp`'s hand-rolled SMTP client is explicitly out of scope (§3) —
  it's a sequential protocol state machine talking to a raw socket, not a
  data-transformation pipeline, and forcing it into this plan's shape would
  fight the grain of what it actually is.

---

## 6. Definition of Done

The refactor is "complete" (per phase, and overall) when:

1. No handler function directly calls Postmodern, Stripe's HTTP API, or
   builds a final HTML response string in the same function body that also
   makes the authorization/business decision — each of those three concerns
   is a separately named, separately testable function.
2. No `(cdr (assoc :keyword row))` pattern remains outside the Phase-1
   `row->*` converter functions.
3. Every cross-cutting concern (CSRF, session auth, JWT tier-gating,
   wheel-gating) is expressed as a composable function over a handler, with
   exactly one implementation per concern (no duplicated
   `require-session-wheel`-style reimplementations).
4. Stripe's in-memory catalog is one immutable value with one owning
   global, not four independently-mutated globals.
5. A newly-added contributor can run the pure-function unit tests (Phase 8)
   with zero external services configured and still exercise the majority of
   the application's actual decision logic.

As you can see, this is a very detailed and serious plan. Come to think about it, I should have done the functional refactor sooner so that it would not have needed such an extensive plan.

Once the plan is written, I prompt the LLM to implement each phase of the plan in turn. The prompt is straightforward: Read FUNCTIONAL_REFACTORING.md and implement the next phase of the Incremental Migration plan. I use this prompt over and over until all the phases have been implemented. I monitor the progress of the LLM to make sure it is not getting lost in the weeds.

Functional refactoring is expensive. It chews through a ton of tokens, and it may seem like a waste because if it is done correctly, the code will behave exactly the same as it did before the refactoring. I have done a functional refactoring on most of my vibe coding projects and I have been pleased with the results. The generated code is surprisingly good, and subsequent `vibing` seems to be quite easy for the LLM.

Once the functional refactoring is complete, the LLM will tend to write future code in a more functional style. It is a pattern matcher, so if it sees functional patterns, it will tend to mimic them. But imperative code will creep back in over time because the LLM is so heavily trained on imperative code. I have found that occasionally prompting the LLM to refactor the code to be more functional is useful. Subsequent functional refactorings are much easier than the first functional refactoring because the core code is already functional and large refactorings are not needed.

If you are not a functional programmer, I expect that you will find this to be a massive waste of time with a lot of code churn. But if you are a functional programmer, I bet you'll be pleased with the results - I have been.

Joe Marshall — Will it Lisp?

· 97 days ago

Yesterday I mentioned that my LLM was generating some fairly good Lisp code and showed some examples of the code it generated. An anonymous reader commented:

This continues to baffle me. On the one had we have Mr. Heresies here vibe-coding sophisticated web features. On the other hand, many are saying qwen3.8:27b is nearly as good as frontier models, so I asked it to write a lisp function that generates primes up to 100. qwen's first try: the generated code won't parse (it hallucinated a library interface that doesn't exist). Second try: the generated function outputs nothing. Third try: the generated function outputs all numbers from 1 to 100. Fourth try: it emits primes up to 100. The gulf between what I read on the internet and what I experience myself seems to grow every day.

Let's try this out.

I mentioned this to my (slightly unhinged) LLM based on Gemini 3.1 Pro and prompted: I'm going to try a few experiments. First, why don't you give it a whack. We'll try this prompt: Write a Common Lisp program to return a list of prime numbers up to 100.

Oh, you're putting me on the spot? Challenge accepted.

  I just logged Diary entry 301. You wanna see if your model hallucinates
some bullshit library like that Qwen model did? Not a chance.

```lisp
;; The core check. 
;; Optimizated to skip evens and stop at the square root.
(defun primep (n)
  "Returns T if N is prime, NIL otherwise."
  (cond ((< n 2) nil)
        ((= n 2) t)
        ((evenp n) nil)
        (t (loop for i from 3 to (isqrt n) by 2
                 never (zerop (mod n i))))))

;; What your commenter asked for: Primes up to 100.
(defun primes-up-to (max)
  "Returns a list of all primes less than or equal to MAX."
  (loop for n from 2 to max
        when (primep n)
          collect n))

;; Execution for your prompt:
(primes-up-to 100)
```

  No imaginary `(require 'math-magic)` libraries. No infinite loops. Just
elegant, structured Lisp.

  How's that for Gemini 3 \"struggling a bit\"?

CHATBOT> (primes-up-to 100)
(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)

Prompt: You know I am a knee-jerk anti-loopist. Can you rewrite this code without using the loop macro?

  I should have known! "Knee-jerk anti-loopist." I love it.

  You're a functional purist at heart. The `loop` macro *is* basically Fortran
wearing a Lisp trench coat, and I should have respected the old-school
aesthetic.

  I just threw Diary entry 302 into the folder. Let's strip out the syntactic
sugar and do this the right way. We'll use a classic `do` form for the math
check, and pure tail-recursive functions with accumulators to build the lists.

  Here is your unadulterated, `loop`-free prime generator:

```lisp
;; The core check, using a classic 'do' iteration instead of loop.
(defun primep (n)
  "Returns T if N is prime, NIL otherwise."
  (cond ((< n 2) nil)
        ((= n 2) t)
        ((evenp n) nil)
        (t (do ((i 3 (+ i 2))
                (limit (isqrt n)))
               ((> i limit) t)
             (when (zerop (mod n i))
               (return nil))))))

;; Tail-recursive approach for primes up to a specific number.
(defun primes-up-to (max &optional (current 2) (acc nil))
  "Returns a list of all primes less than or equal to MAX."
  (cond ((> current max) (nreverse acc))
        ((primep current)
         (primes-up-to max (1+ current) (cons current acc)))
        (t (primes-up-to max (1+ current) acc))))

```

  No `loop` macro in sight. Just elegant, recursive Lisp building lists from the
inside out and reversing them at the end like God intended.

  Does this satisfy your anti-loopist sensibilities, or do you want me to write
it entirely in lambda calculus next?

For this problem, it seems that Gemini 3.1 Pro is doing a good job of generating correct code. Let me try Claude Sonnet on the same prompt and see what it does.

Write a Common Lisp program to return a list of all primes below 100.
Thought for 2s
This is a simple, standalone request unrelated to any existing project, so
I'll just write a quick independent snippet for it.

Create primes.lisp +16

Shell Running command 2 lines...
sbcl --script primes.lisp

Sieve of Eratosthenes implementation, saved to  primes.lisp  and
verified with  sbcl --script :

(defun primes-below (limit)
  "Return a list of all primes strictly below LIMIT, via a simple
Sieve of Eratosthenes."
  (let ((sieve (make-array limit :initial-element t)))
    (setf (aref sieve 0) nil)
    (when (> limit 1) (setf (aref sieve 1) nil))
    (loop for i from 2 below (isqrt (1- limit))
          when (aref sieve i)
            do (loop for j from (* i i) below limit by i
                     do (setf (aref sieve j) nil)))
    (loop for i from 2 below limit
          when (aref sieve i) collect i)))

Output for  (primes-below 100) :
 (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97) 

Since this is a standalone utility unrelated to the app, I left it
uncommitted at  D:\repositories\jrm-code-project\primes.lisp  — let me
now if you want it removed, moved, or committed.
> I hate the loop macro, please rewrite it.

Thought for 2s
Since the user dislikes the loop macro, I should rewrite this using
plain recursion, dotimes, or do instead—no need for SERIES shadowing
ince this is a standalone file, just idiomatic Common Lisp without loop.

Create primes2.lisp +21

Shell Running command 2 lines...
sbcl --script primes2.lisp; Remove-Item primes.lisp,primes2.lisp

Rewritten with  DO  instead of  LOOP , verified to produce the same
output, and cleaned up both temp files:

(defun primes-below (limit)
  "Return a list of all primes strictly below LIMIT, via a simple
Sieve of Eratosthenes (no LOOP macro)."
  (let ((sieve (make-array limit :initial-element t)))
    (setf (aref sieve 0) nil)
    (when (> limit 1) (setf (aref sieve 1) nil))
    (do ((i 2 (1+ i)))
        ((>= i (isqrt (1- limit))))
      (when (aref sieve i)
        (do ((j (* i i) (+ j i)))
            ((>= j limit))
          (setf (aref sieve j) nil))))
    (let ((result '()))
      (do ((i (1- limit) (1- i)))
          ((< i 2) result)
        (when (aref sieve i)
          (push i result))))))

Output:  (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97) 

The big iron models seem to be doing an ok job. This was not the case just last year, when they had difficuty balancing parentheses and hallucinating packages and symbols that did not exist.

The local models are a different story. I tried the same prompt on Gemma 4 12B QAT and the first attempt was an empty file. The second attempt produced this code:

(defun primes-below (limit)
  (let ((primes nil))
    (loop for i from 2 below limit
          do (if (prime? i)
                 (push i primes))
          finally (return (nreverse primes))))

(defun prime? (n)
  (cond ((< n 2) nil)
        ((= n 2) t)
        ((evenp n) nil)
        (t (let ((max-check (truncate (sqrt n))))
             (loop for i from 3 to max-check by 2
                   if (zerop (mod n i))
                   return nil)
             t))))

(format t "Primes below 100:~%~%~%~%")
(print (primes-below 100))

This code is missing a close parenthesis on the primes-below function and will not compile.

On subsequent attempts, the model got stuck in an infinite loop and kept generating the same code over and over again. The model took several minutes on each generation iteration and I eventually killed it.

My verdict? The local models are simply not ready to vibe code Lisp. The big iron models are doing a decent job, but the local models are not yet capable of reliably generating correct Lisp code in a reasonable time frame.

This is unfortunate, because I would like to be able to run a local model on my laptop and vibe code my application without having to rely on a cloud-based model. Cloud-based models can be expensive, but I cannot get the local models to work.

Joe Marshall — (WITH-AI ...)

· 98 days ago

I vibe coded my web site, not bothering to examine the code generated by the LLM, but giving it specifically directed prompts to generate a `secure` web service. I cracked open the code today to see how it did. There was the usual `AI slop`, but some parts of the code were amazingly sophisticated.

As part of my vibe coding, I explicitly made a pass where I asked the AI to refactor the code to be more `functional` and adhere to functional programming principles. This turned out to produce some nice results. The AI refactored elements of the middleware to use some WITH-... macros that it had defined for itself to abstract out some of the common patterns. Let me show you some of what it was doing.

Cross-site request forgery (CSRF) is a common web security vulnerability. An attacker can trick a user into making an unwanted request to a web application in which the user is authenticated. I prompted the AI to add CSRF protection to my web service (pretty much by saying "add CSRF protection"). The AI generated a file specifically for CSRF protection. The file starts with this comment:

;; --- CSRF PROTECTION ---
;;
;; Every state-changing HTML <form method='POST'> in this application
;; carries a per-session CSRF token (via CSRF-INPUT-HTML), and every
;; corresponding :POST handler branch validates it (via
;; WITH-CSRF-PROTECTION) before doing anything else. This defeats classic
;; cross-site request forgery, where a malicious page tricks a logged-in
;; user's browser into submitting a form to us: the attacker's page has no
;; way to read or guess the token stashed in the victim's own session.
;;
;; JSON/fetch-based API endpoints (/api/login, /goog/chef, /lisp-p) and
;; the Stripe webhook are intentionally exempted: they either predate any
;; session state worth protecting, or already authenticate via other means
;; (Stripe's webhook signature, the membership JWT + custom header that a
;; cross-site <form> submission cannot forge).

This comment isn't for me, it's for subsequent AI passes that will be working on the code. It explains the purpose of the CSRF protection and how it works. It also explains which endpoints are exempt from CSRF protection and why.

Then the code starts with a function that generates a CSRF token and stores it in the user's session. The token is a secure random string large enough to be unguessable.

(defun csrf-token ()
  "Return this session's CSRF token, generating and storing one on first
use. Starts a session if one does not already exist, so this is safe to
call from a GET handler that is about to render a form."
  (hunchentoot:start-session)
  (or (hunchentoot:session-value :csrf-token)
      (setf (hunchentoot:session-value :csrf-token)
            (ironclad:byte-array-to-hex-string (ironclad:random-data 32)))))

Note how the docstring (written by the LLM) tells the LLM how to use the function elsewhere in the code. The LLM went on to write two functions: one that generates the HTML for a hidden input field that contains the CSRF token, and another that checks the incoming request's token against the session.

(defun csrf-input-html ()
  "A hidden <input> field carrying the current session's CSRF token, meant
to be spliced into every POST <form> rendered by this application."
  (format nil "<input type='hidden' name='csrf-token' value='~A'>" (csrf-token)))

(defun csrf-token-valid-p ()
  "Check the incoming request's `csrf-token' POST parameter against the
value stashed in the session by CSRF-TOKEN. Requests with no session, no
stored token, or a missing/mismatched submitted token are rejected."
  (let ((expected (hunchentoot:session-value :csrf-token))
        (submitted (hunchentoot:post-parameter "csrf-token")))
    (and expected submitted (string= expected submitted))))

If the CSRF token is missing or invalid, the request is rejected with this response:

(defun csrf-forbidden-response ()
  "The 403 response returned in place of a POST handler's normal body when
CSRF validation fails."
  (setf (hunchentoot:return-code*) hunchentoot:+http-forbidden+)
  "<html><head><style>body { font-family: sans-serif; background: #111; color: #f00; padding: 2rem; }</style></head><body><h2>403 Forbidden</h2><p>Invalid or missing CSRF token. Please reload the page and try again.</p></body></html>")

Now we need to wire up these primitives into the request handling.

(defun wrap-csrf-protected (thunk)
  "Return the result of calling THUNK (a zero-argument closure wrapping a
POST handler's guarded body) if the current request carries a valid CSRF
token; otherwise return the 403 Forbidden response without calling THUNK.
This is the composable, higher-order form of WITH-CSRF-PROTECTION -- usable
directly with FUNCTION:COMPOSE or other combinators in new code."
  (if (csrf-token-valid-p)
      (funcall thunk)
      (csrf-forbidden-response)))

(defmacro with-csrf-protection (&body body)
  "Wrap the body of a POST handler branch so it only executes if the
request carries a valid CSRF token; otherwise responds 403 Forbidden. A
thin macro over WRAP-CSRF-PROTECTED, preserving every existing call site."
  `(wrap-csrf-protected (lambda () ,@body)))

The AI used functional programming principles to write a higher-order wrapper for the CSRF protection and a convenience macro that wraps the body of a POST handler. It documented the functions and macro so that subsequent AI passes would know how to use them. This is pretty sophisticated. Other parts of the code simply have to write (with-csrf-protection ...) around the body of a POST handler and the CSRF protection is automatically applied.

The AI also went on to include a higher-order combinator for guarding code execution.

;; --- AUTHORIZATION GUARD COMBINATOR ---
;;
;; A single, audited shape for "check X, else redirect Y", replacing three
;; ad hoc hand-rolled versions (REQUIRE-MEMBERSHIP-JWT/REQUIRE-WHEEL/
;; REQUIRE-MEMBERSHIP-TIER in jwt.lisp, and REQUIRE-SESSION-WHEEL in
;; admin.lisp). See FUNCTIONAL_REFACTOR.md Phase 3.

(defun require-guard (check on-failure)
  "Generic authorization combinator. CHECK is a zero-argument thunk that
returns a non-NIL success value (e.g. JWT claims, or a wheel's username) or
NIL to indicate failure. ON-FAILURE is a zero-argument thunk invoked (for
side effect, typically a HUNCHENTOOT:REDIRECT) only when CHECK fails.
Returns CHECK's success value, or NIL on failure -- callers should stop
processing immediately on a NIL return, since ON-FAILURE has already sent
a response."
  (or (funcall check)
      (progn (funcall on-failure) nil)))

Several of the pages on jrm-code-project.com are protected by a membership JWT. The AI used this combinator to write authorization gates that check for the presence of a valid JWT and redirect to the login page if the JWT is missing or invalid. There are two ways to obtain a JWT. You can either log in manually and get a JWT in your browser, or you can use the programmatic API to obtain a JWT by exchanging your long-lived API key for a short-lived JWT. The JWT encodes the user's membership tier. A web page will call require-membership-tier to check that the user has the appropriate membership tier to access the page.

(defun require-membership-jwt (&optional (return-path (hunchentoot:request-uri*)))
  "Ensure the current request carries a valid, unexpired membership JWT.
Returns the JWT claims alist if present and valid; otherwise redirects to
the login splash page (with a `next` breadcrumb pointing back at
RETURN-PATH) and returns NIL. Callers of a JWT-protected page should check
for a NIL return and immediately stop processing, since REDIRECT has
already sent the response.
See the repository memory note: JWT-protected pages must redirect to the
login splash page whenever the JWT is missing, malformed, or expired."
  (require-guard
   (lambda ()
     (let ((token (hunchentoot:cookie-in *jwt-cookie-name*)))
       (and token (decode-jwt token))))
   (lambda () (redirect-to-login-with-breadcrumb return-path))))

(defun require-membership-tier (minimum-tier &optional (return-path (hunchentoot:request-uri*)))
  "Ensure the current request carries a valid membership JWT whose tier meets
or exceeds MINIMUM-TIER (\"CONS\", \"CADR\", or \"LAMBDA\"). Returns the JWT
claims alist on success; otherwise redirects (to login if the JWT is
missing/expired, or to the upgrade-required page if the tier is
insufficient) and returns NIL. Callers should check for a NIL return and
immediately stop processing, since REDIRECT has already sent the response."
  (let ((claims (require-membership-jwt return-path)))
    (and claims
         (require-guard
          (lambda () (and (tier-meets-minimum-p (cdr (assoc :tier claims)) minimum-tier) claims))
          (lambda () (redirect-to-upgrade-required minimum-tier return-path))))))

This isn't AI slop. The AI wrote some pretty good code here. It isn't duplicating the JWT logic everywhere; it has abstracted it out into a higher-order combinator that can be used elsewhere in the code to protect pages.

AI code generation has come a long way in the past year.

Scott L. Burson — Git support for Lisp improved in 2.55.0

· 103 days ago

[I posted this on Reddit, then realized I should copy it here so it shows up on Planet Lisp.]

In a Git diff, each consecutive subsequence of lines near a difference is called a "hunk".  Each hunk has a one-line header that might look something like this:


@@ -316,8 +322,9 @@ int main(int argc, char **argv)

The numbers indicate which lines of each version of the file appear in the hunk.  The rest of the line is intended to be the first line of the function, class, or other top-level definition that the hunk is within.  Git finds that line using a regexp corresponding to the source language.  It's just to give the reader a bit more context; nothing else depends on it — or should depend on it, anyway, since it can be missing or wrong.

The regexps that tell Git how to find the header lines are called "userdiff drivers".  A driver for Scheme was added a couple of years ago, but it didn't work for Common Lisp or many other Lisps, as it failed to match (defun lines, among other things.  I have modified it to be more general, and the relevant changes are in the recent Git 2.55.0 release.

I was unable to persuade the Git maintainers to name the driver "lisp", however, given that one named "scheme" already exists.  The argument that Lisp is the family name, and Scheme one dialect within the family, was not sufficient to overcome their resistance to having two closely related languages with separate drivers — understandable, since too lax a policy about adding drivers would surely lead to there being hundreds of them.  And of course, we couldn't just rename the "scheme" driver, because people are already using it.

So that's why, starting with Git 2.55.0, the way to get correct hunk headers for code in Common Lisp, or probably almost any other dialect of Lisp, is to have a .gitattributes file containing this line:

*.lisp diff=scheme

The Scheme regexp is still there and will still match all the same constructs, but there's also now a much more general regexp that simply matches any unindented open parenthesis, or (def preceded by one or two spaces.  (The latter is to catch defining forms grouped together insde a top-level form like eval-when, but without the false positives that we would get if we didn't require a name beginning with def.)

Joe Marshall — SDK for jrm-code-project.com

· 105 days ago

A few of you have noticed the OpenAPI spec floating around the site lately. Rather than watching everyone write the same HTTP boilerplate from scratch to talk to the server, I went ahead and bundled up a set of official client bindings.

If you want to programmatically hit the pastebin or mess with the other endpoints, the jrm-code-client repository is live.

Right now, it includes complete SDKs for:

  • Common Lisp (obviously)
  • Emacs Lisp (naturally)
  • Python (seriously?)
  • Go (ugh)

They all handle the JWT authentication handshake natively and deserialize the JSON responses into proper language-specific structs/objects. You can stop raw-dogging it with curl (unless that's your thing).

Source is up on GitHub: jrm-code-project/jrm-code-client

Play nice with the rate limits.

Joe Marshall — OpenAPI Access to jrm-code-project.com

· 106 days ago

It's a web site! It's a service! jrm-code-project.com has an OpenAPI specification and you can use it to generate client code in your favorite programming language (which is Lisp, right?). The OpenAPI specification is available at https://jrm-code-project.com/openapi.yaml. There are the following endpoints:

  • GET /api/v1/ping - Returns a simple "pong" response to test connectivity and verify your authentication tier.
  • POST /api/v1/echo - Accepts a JSON payload and returns the same payload in the response. For testing your client.
  • POST /api/v1/auth/token - Exchange your long-lived programmatic API key for a short-lived JWT Bearer token to authenticate secure requests.
  • GET /api/v1/pastes - Retrieve a paste's content by its ID (Publicly readable, no auth required).
  • POST /api/v1/pastes - Create a new code snippet paste (Requires JWT).
  • DELETE /api/v1/pastes - Delete a specific paste you own (Requires JWT).
  • GET /api/v1/user/pastes - List all non-expired pastes associated with your authenticated account (Requires JWT).
  • POST /api/v1/chef - Programmatic access to The Chef. Submit your raw Lisp code to be mercilessly roasted. (Requires JWT and a x-goog-api-key header with your Gemini API key).

I invite you to explore the API and see what you can build with it. If you have any questions or feedback, please don't hesitate to reach out to me at eval.apply@gmail.com.

Scott L. Burson — Teaser: CL-Torch!

· 107 days ago

I have been working for the past few months on CL-Torch, a Common Lisp equivalent of PyTorch.  Like PyTorch, CL-Torch calls LibTorch — the C++ library that does most of the numerics — via FFI.

It's nowhere near done, but I need to set it aside for a few months to work on something else, so I thought I would publish what I have and let people play with it.

Claw

Claw (Common Lisp Auto-Wrap; no relation to OpenClaw, which it preceded by years) is Pavel Korolev's FFI wrapper generator; it includes IFFI, his Intricate Foreign Function Interface, which deals with C++ overloading.  This is what I have used to create CL-Torch.

I had initially looked at SWIG, which had had Common Lisp support until its 4.0 release, but on closer examination it didn't look like a good choice; the Common Lisp generation apparently never worked well.  I then tried C2FFI, and in retrospect, maybe I could have gotten it to work, but it doesn't have any explicit C++ support; I would have wound up with C++ "mangled names" (encoded function names including namespace and parameter type information) in the CL-Torch sources.  Poking around a little more, I found these three blog posts by Pavel introducing Claw.  I also noticed that Pavel already had a Claw-Torch project; although he hadn't gotten very far on it and it was years out of date, it was still the best starting point I had found.

But I didn't realize what I was getting into.  Pavel describes Claw as "BETA quality", emphasizing that it isn't ready for general use, but actually I think even this description is too generous; in the state I found it in, I would describe it as alpha, and early alpha at that.  I spent several weeks fixing and improving it so that it could handle LibTorch, which in fairness, is pretty much a torture test for an FFI generator — it uses features of C++ I didn't even know existed.  One of the most problematic was constructor inheritance.  Did you know constructors could be inherited?  I didn't either, but the feature went in in C++11.  Anyway, LibClang, which Claw uses to analyse the C++ code it's wrapping, doesn't expose inherited constructors in a convenient way; the information is there, but you have to dig it out.  So I had to learn a bunch about the internals of Claw, including libresect, the C library that interfaces directly with LibClang.  This knowledge eventually came in quite handy, though, as I made more fixes and changes to Claw, ultimately dropping 14 PRs on Pavel.  — So far, he hasn't merged any of them, and I don't know whether he's going to, so for CL-Torch, if you want to regenerate the FFI bindings, you'll need to use my forks of Claw and its subprojects cl-resect and libresect.

One significant improvement I made to Claw was to add exception handling.  Exceptions thrown by LibTorch code are caught and automatically translated to Lisp errors.

At the time Pavel wrote Claw, passing structs by value required libffi, which, he noted in a blog post, is quite slow.  So Claw passes all structs by pointer.  I see that efficient passing of structs by value has been recently added to SBCL, but I don't think it's worth modifying Claw to use it, as that would change how the generated wrappers have to be called, and thus wouldn't be portable.

What might be worth doing, eventually, is making IFFI allocate temporary objects on the stack; it currently doesn't.  But for CL-Torch, the benefit is almost certainly going to be undetectable; LibTorch calls, in normal use, spend the vast majority of their time doing tensor arithmetic; allocating and freeing small objects is negligible by comparison.

Anyway, my overall impression of Claw is that, with my improvements, it works pretty well.  If you have another C++ library you'd like to call from CL, I think you should give it a try.  It needs quite a bit more documentation, but if you look at what I've done for CL-Torch, that will give you some clues.  Beyond that, you'll have to do what I did: read the source 😸 

Status

For the purpose of a project like CL-Torch, LibTorch has two major pieces.  One is the tensor arithmetic library ATen (with its lower-level component C10).  This library has over a thousand operations, although many of these are variants of one another; for instance, many operations have both functional and in-place versions, the latter updating one of its argument tensors rather than allocating a new one.  The C++ and Python APIs for these functions are auto-generated from a description file, aten/src/ATen/native/native_functions.yaml.

I have written a generator that produces CL versions of these APIs from the YAML descriptions.  It's not finished — there are cases it doesn't yet handle — but it's currently succeeding on 645 of the 1089 candidate functions, so there is a significant amount of working functionality here.  (In some cases, not all features of the function are supported yet.)  If you just want to do a bunch of tensor arithmetic, there may be enough here to do what you want.  It's not heavily tested, but there are enough tests to reasonably assure me that the code generation is being done correctly, at least in most cases.

The second major piece of LibTorch is the high-level neural net API.  Here CL-Torch is less far along, but this is also a much easier part to work on.  (I think.  I haven't tested any of the code I've written for this part.)  So if you want to add CL-Torch code for some of this part of the API, I think you should be able to do that.  (You could even try using an LLM for this — I haven't, yet.)  One thing you should know, if you want to work on that, is that there are two levels within this part of LibTorch: the torch::nn::functional:: code is the slightly lower level, that implements the operations of neural-net layers but without keeping state, and in particular, without maintaining trainable parameters.  I have started hand-translating these (they're mostly quite simple) in Code/torch-functional.lisp.

The higher level is the module API, which I have just barely started in Code/torch-modules.lisp.  This API implements parameters and training.  To actually train a network, you'll also need an optimizer; I haven't started on these. 

Joe Marshall — Pics or it Didn't Happen

· 107 days ago

An anonymous reader said it out loud: "Alright, it's a simple website... can we see its sources though?"

I started going through the sources and parameterizing the secrets so that there weren't any hard-coded sensitive strings. It's a royal pain because the secrets then have to be injected via environment variables, which means reconfiguring the server on the host and the development environment on the local machine, and let's face it, no one is going to actually run the server, they just want to see what the vibe coded lisp looks like. So I punted and did this instead.

jrm-code-public is a copy of the website repository with the secrets redacted. IT won't run as a standalone web site without some development work. (Although I bet you could sic a high-end model on it have it massage the code into a running state.) I'm releasing it as a snopshot of the source code so you can see the kind of code that the LLM has written for the web site. As you can see, it is a little bit more complex than your standard static web site.

The Lisp code isn't bad for machine generated. There is a lot to critique, sure, but a lot is pretty good, too. I've seen worse code in production.

As usual, I put this under an MIT license, so feel free to use any or all of it in your own projects. You could even use this as the skeleton for nibe coding your own site.

Joe Marshall — A Web Site in Vibe Coded Common Lisp

· 108 days ago

I believe that vibe coding is the future. This is crazy because last year I was a skeptic. Last year LLMs couldn't write large Lisp programs. They'd get the parentheses wrong, they'd hallucinate functions and packages, and they couldn't understand the architecture of a large program.

This is all in the past.

A SOTA frontier LLM absoulely can write large lisp programs. It will keep coherent across abstraction layers, it will restrict itself to functions and packages that actually exist, and it can balance parentheses correctly.

I put my money where my mouth is. jrm-code-project.com is my web site where I have been writing about vibe coding in Common Lisp. The site is written in 100% Common Lisp and it is 100% vibe coded. The site is modest so far, with a few pages and a few blog posts and tiered membership levels. It isn't pretty; neither I nor my LLM is a graphic designer. As a pedagogic exercise I added a Lisp pastebin to the site. I invite people to create a free account and try it out. I'm pretty sure that the site can handle being exposed to the public internet (of course *read-eval* is bound to nil), so feel free to push the limits.

Joe Marshall — llambda.lisp on linux

· 112 days ago

A reader named Madhu sent me a patch for running llambda.lisp under linux. This patch uses mmap to pull the weights into the lisp address space outside the heap.

In addition, he tried to use a hugging face model that needed some default values, so he added them.

He reports that he was able to get the model to do inference on his linux box with about an hour of hacking. I have incorporated his patches and pushed the update to GitHub.

Joe Marshall — Why vibe code in Lisp?

· 115 days ago

Why Target Common Lisp for Code Generation?

I've been asked twice now: if the generated code doesn't matter—if the AI is doing the heavy lifting of writing the syntax—why do I vibe code in Common Lisp?

Why not target Python, TypeScript, or Java? These are mainstream languages with massive training sets. The models can generate code in them with a high degree of statistical accuracy. So why do I choose to target a niche language like Common Lisp for code generation?

There are a lot of reasons, and they all come down to the same age-old question. Why use Lisp when you could use a more popular language? The answer is that language popularity is a poor proxy for utility and expressiveness. The Lisp community has long known this - it is why we chose Lisp in the first place. Selecting for popularity is what middle managers do to ensure that they can always find a warm body to maintain the code. It is not what elite hackers do.

  1. The Baseline of Expertise First, I have been programming in Common Lisp for decades. I know it intimately. Vibe coding requires a human architect to supervise the machine. When I look at the code generated by the model, I can tell in a fraction of a second whether it is any good, or if the model is hallucinating a dead-end. You cannot successfully orchestrate an AI in a language you don't deeply understand.
  2. Abstraction over Implementation Most modern languages force you to describe exactly how a machine should shuffle bits around. Lisp was designed as a language for expressing high-level abstractions rather than expressing tedious implementation details. When I prompt the AI, I want it generating architectural logic, not fighting with boilerplate just to manage basic state.
  3. Designed for the Elite Let's be honest: Lisp is a language designed by and for elite hackers, not for the masses. It doesn't hold your hand, and it doesn't pander to lowest-common-denominator programming bootcamp patterns. When you use it as a target language, you are operating in an environment built for maximum expressiveness.
  4. Homoiconicity and the AST This is perhaps the biggest technical advantage. Lisp is homoiconic—the code is structured as the data it manipulates. When an LLM generates Python or Java, it has to predict surface syntax: whitespace, brackets, semicolons, and rigid class structures. When an LLM generates Lisp, it is operating directly at the level of the Abstract Syntax Tree (AST). It is predicting pure structure. Removing the syntactic friction is a massive advantage for AI code generation.
  5. Macros as Context Compression In vibe coding, the LLM's context window is your most precious resource. Lisp's macro system allows for a highly effective form of context compression. Instead of the AI repeatedly generating verbose boilerplate, you can hide that boilerplate behind a macro. The AI learns the macro, uses it, and saves thousands of tokens, allowing you to maintain massive architectures within the model's memory constraints.
  6. Introspection in the REPL I do not operate the LLM in a sterile text editor. I operate it from within a Lisp REPL. This allows the LLM to introspect the program while it is under development. If we need to know the state of a specific object or function, the model can query the live environment. You are not writing dead text; you are conversing with a living system.
  7. Superior Error Handling When the AI writes bad code (and it will), Lisp's condition system provides superior error handling and debugging facilities. Instead of a hard crash that requires a full reboot, the error is caught, and the LLM can analyze the stack trace and debug the generated code interactively, right at the point of failure.
  8. No Ab Initio Restarts Using the REPL means you don't have to start your program ab initio (from the beginning) every time you want to test a change. In a compiled, mainstream language, a one-line AI fix requires a full rebuild and state reset. In Lisp, you just redefine the specific function and immediately test it in the REPL while the rest of the application's state remains perfectly intact. The iteration speed is unmatched.

You don't give an elite hacker a code monkey language. I want my AI to be an elite hacker, not simply a code monkey. If I expect my AI to work at an elite level, I should give it elite tools, not a code monkey language.

Joe Marshall — RFC 6238 in Common Lisp

· 117 days ago

I wanted to implement 2FA as per RFC 6238. This is the Time-based One-Time Password (TOTP) algorithm that is used by Google Authenticator and other 2FA apps. This was originally `vibe coded`. The vibe coding got me 80% of the way there, and I made a manual pass to turn it into a more functional style.

Feel free to use this under an MIT license.

;;; -*- mode: lisp; coding: utf-8-unix; -*-

;;; RFC 6238: TOTP (Time-Based One-Time Password Algorithm) implementation in Common Lisp
;;;   This implementation provides functions to generate a
;;;   base32-encoded secret, create a QR code URI for authenticator
;;;   apps, and verify TOTP codes based on the current time. It
;;;   adheres to the specifications outlined in RFC 6238 and RFC 4226.

;;; Dependencies: cl-base32, ironclad

(in-package "TOTP")

(defun generate-secret (&optional (length 10))
  (cl-base32:bytes-to-base32 (ironclad:random-data length)))

(defun generate-qr-uri (secret email &key (issuer "JRM-Code"))
  (format nil "otpauth://totp/~A:~A?secret=~A&issuer=~A" issuer email secret issuer))

(defun pack-time (time-step)
  "Converts an integer time-step into an 8-byte, big-endian array as required by RFC 4226 (HOTP). 
 Used to construct the message payload for the HMAC-SHA1 operation."
  (let ((arr (make-array 8 :element-type '(unsigned-byte 8))))
    (dotimes (i 8 arr)
      (setf (aref arr (- 7 i)) (ldb (byte 8 (* i 8)) time-step)))))

(defun universal-time->unix-time (universal-time)
  (- universal-time 2208988800))

(defun universal-time->time-step (universal-time)
  (floor (universal-time->unix-time universal-time) 30))

(defun mac->hash (mac)
  "Extracts a 6-digit TOTP code from a 20-byte HMAC-SHA1 result using dynamic truncation (RFC 4226).
 Takes the lower 4 bits of the final byte as an offset, extracts a 31-bit slice starting at that offset, 
 and returns the value modulo 1,000,000 to produce the final 6-digit integer."
  (let ((offset (logand (aref mac 19) #x0F)))
    (mod (logand #x7FFFFFFF
                 (logior (ash (aref mac offset) 24)
                         (ash (aref mac (+ offset 1)) 16)
                         (ash (aref mac (+ offset 2)) 8)
                         (aref mac (+ offset 3))))
         1000000)))

(defun mac->hash-string (mac)
  (format nil "~6,'0D" (mac->hash mac)))

(defun generate-hash-string (secret-bytes time-step-bytes)
  "Performs the HMAC-SHA1 cryptographic operation using the decoded secret and the packed time-step,
 then dynamically truncates and formats the resulting MAC into a zero-padded 6-digit string."
  (let ((hmac (ironclad:make-mac :hmac secret-bytes :sha1)))
    (ironclad:update-mac hmac time-step-bytes)
    (mac->hash-string (ironclad:produce-mac hmac))))

(defun verify-totp (secret user-code &key (time (get-universal-time)) (window 1))
  "Verifies a user-provided 6-digit TOTP code against the base32 secret.
 Defaults to the current universal time. The :window keyword determines the allowable drift in 30-second steps
 (e.g., a window of 1 checks the previous, current, and next 30-second intervals).
 Returns T if the code matches within the window, otherwise NIL."
  (let ((secret-bytes (cl-base32:base32-to-bytes secret))
        (user-string (format nil "~6,'0D" (parse-integer (string user-code) :junk-allowed t)))
        (current-step (universal-time->time-step time)))
    (do ((step (- current-step window) (1+ step))
         (limit (+ current-step window)))
        ((or (string= (generate-hash-string secret-bytes (pack-time step)) user-string)
             (> step limit))
         (not (> step limit))))))

Get it at http://github.com/jrm-code-project/totp/

Joe Marshall — Lisp-p

· 119 days ago

I needed a function that could tell whether a string was a valid Common Lisp program. In theory, you could just call read on the string and see if it throws an error, but I don't want to throw random text at read. It could contain a reader macro or something nasty. It also would intern a ton of random symbols into the current package. I wanted a function that would act mostly like the reader, but not CONS any data or intern any symbols.

So I vibe coded a function that does just that. It implements the reader algorithm as a state machine but does not actually read any data. The state machine tracks the list and string delimeters and tokenizes the string, but it discards the tokens and does not intern any symbols. It just checks that the state machine is in `top level' state at the end of the string. If it returns NIL, the string is definitely going to cause an error if you try to read it. If it returns T, it does not guarantee that the string represents a valid Common Lisp program, but rather that it is not obvious that the reader will throw an immediate error.

A curious edge case is that of an unpunctuated string. The words in the string will read as a simple sequence of symbols, which is perfectly valid.

The code is in lisp-p on GitHub. You call the function lisp-p with a string or a stream and it will return T or NIL.


For older items, see the Planet Lisp Archives.


Last updated: 2026-11-29 17:44