01 Dec 2026

feedPlanet 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

feedPlanet 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

feedPlanet 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:

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

feedPlanet 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

feedPlanet 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 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:

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

feedPlanet 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:

\[ \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. ↩︎

24 Nov 2026 12:00am GMT

17 Nov 2026

feedPlanet 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:

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.


🕊

17 Nov 2026 2:38pm GMT

07 Nov 2026

feedPlanet 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:

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:

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:

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

07 Nov 2026 1:12pm GMT