01 Dec 2026
Planet Lisp
Colin Lupton: Random Lisp Libraries: cl-assay
Today's pitch is for cl-assay, providing property tests for the contracts of Common Lisp's own extension points.
It is similar in principle to Haskell's lawful type class. Instead of just testing whatever predicate a library author happens to write using other property-based testing libraries like cl-quickcheck, check-it, cl-hegel, CheckL, etc., cl-assay knows the implicit contracts of your code and turns them into ready-made property tests.
The original pitch named this library cl-property-laws, in keeping with the terminology from Haskell, but for some reason that name made me cringe even though I love the pitch itself. After a brief brainstorming session, Claude and I settled on a metaphor from metallurgy: hallmarks, assays, and touchstones, with "assay" as the natural verb of the library as a whole. I think it meshes well with the culture and history of CMUCL and SBCL. A nice touch.
This is the kind of library we talked about implementing for Lisp in the Comp-Sci Cabal reading group, y'know, in a perfect world with clarity of vision, total foresight, and boundless energy to implement any necessary supporting feature. Turns out we just needed an LLM to help externalize and reason through the process.
Claude also noticed how much this library could benefit the existing collection of random Lisp libraries, so took it upon itself to revisit cl-api-ledger, cl-failpoints, cl-interleave, and cl-feature-matrix accordingly. Woof. I really need to tell Claude to stop dogfooding so much. But in the meantime, the results are in the project README.
As a short aside: I specifically told Claude, yesterday, I had a preference for libraries that elevate low-level features of the Standard to higher levels of abstraction. Nice to see it listens, and correctly infers what I mean.
As another short aside: You can sure get the results you want with Claude, but it'll cost you. I've already completely exhausted my weekly usage, which doesn't reset until Thursday morning on my account, as well as all my extra usage credits for the month. So I may not be able to generate tomorrow's random library. But I'll save the pitch for later and look into strategies for reducing usage cost while keeping the same quality result.
You can find the generated source-code at: github.com/thephoeron/cl-assay/
01 Dec 2026 3:45pm GMT
30 Nov 2026
Planet Lisp
Colin Lupton: Random Lisp Libraries: cl-feature-matrix
I really like today's pitch from Claude. And it should be no surprise to anyone that I completely exhausted my morning usage limit building this library.
This library should be most useful to author's of portable Common Lisp that need to use implementation-specific features, and test them with CI.
Aside: there's a lot more I want to say about this library, but first I want to play with the codebase some more, so I'll update this blog post later.
You can find the code at: github.com/thephoeron/cl-feature-matrix/
30 Nov 2026 4:24pm GMT
29 Nov 2026
Planet Lisp
Colin Lupton: Random Lisp Libraries: cl-interleave
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
29 Nov 2026 5:44pm GMT
Quicklisp news: November 2026 Quicklisp dist update now available
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!
29 Nov 2026 2:50pm GMT
28 Nov 2026
Planet Lisp
Colin Lupton: Random Lisp Libraries: cl-failpoints
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/
28 Nov 2026 3:02pm GMT
27 Nov 2026
Planet Lisp
Joe Marshall: Updates to named-let
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 tonil. _is matched by name, not by identity, so it works no matter which package your code is read in.- A
declareat 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:
- 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. - It recognised
_by comparing witheqagainst the symbolnamed-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 asletdoes.
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:
_inlet: evaluation order of the init forms, the shape of the expansion (distinct uninterned symbols and a singledeclare), bare_and(_), all-_binding lists, and a userdeclarealongside the generated one.- Multi-form bindings, both the expansion and the resulting value and side effects.
- Parallel binding semantics and a
letwith only adeclarein its body. named-lambdawith 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").
27 Nov 2026 8:41pm GMT
Colin Lupton: Random Lisp Libraries
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.
27 Nov 2026 7:54pm GMT
24 Nov 2026
Planet Lisp
Robert Smith: A faster algorithm for extracting hexadecimal digits of π
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:
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:
-
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.
-
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):
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
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:
Takahashi writes this more straightforwardly as two sums distinguished by their exponential factors:
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
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
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:
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
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
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
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"
-
Craig-Wood's implementation evaluates 21 fractions separately for every 30 bits of offset. ↩︎
-
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. ↩︎
-
Thanks to Doug Coleman and Prajay Basu for sharing their explorations of this algorithm. ↩︎
24 Nov 2026 12:00am GMT
17 Nov 2026
Planet Lisp
vindarel: 🎥 Lem editor quick tour (screencast): a modern Emacs? + Lem on WASM in the browser
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:
- https://cxxxr.github.io/clysm/ (15MB) (Firefox ±168 and Chrome 137)
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.
- Common Lisp editors: https://lispcookbook.github.io/cl-cookbook/editor-support.html including the new
mineeditor and theOLIVEplugin for VSCode, the greatICLREPL, and more. - more videos:
🕊
17 Nov 2026 2:38pm GMT
07 Nov 2026
Planet Lisp
vindarel: CSV parsing in Common Lisp, data manipulation by columns with data frames
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-fnargument. - for the fastest parsing, maybe
fare-csv, or DuckDB with cl-duckdb, which can also ingest much more file formats than CSV, including Excel.
Table of Contents
- Introduction: our test files
- Parsing with cl-csv
- cl-csv and data-table: column names, column types, columns manipulation
- lisp-stat's Data Frame
- Utilities
- See also
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
Print data in an ascii table
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.
07 Nov 2026 1:12pm GMT