close
  • chevron_right

    Call for review: package-local nicknames on CLISP

    Michał "phoe" Herda · 5 days ago - 20:04 edit

#CommonLisp #Lisp

Joram Schrijver, known as mood on Freenode, has implemented package-local nicknames on CLISP.

If anyone is anyhow familiar with the CLISP codebase and is capable of reviewing that merge request, please review it - it is an important last step in pushing support for package-local nicknames across all of the Common Lisp ecosystem. (They are already supported by SBCL, CCL, ECL, Clasp, ABCL, ACL, and will be supported in LispWorks 7.2)

  • chevron_right

    Parentheses and indentation

    Michał "phoe" Herda · Monday, 18 May - 19:23 edit · 6 minutes

#CommonLisp #Lisp

Claim: You know you've got used to reading Lisp when you no longer care about the parentheses and instead read Lisp by indentation. And this is how it is supposed to be read.

(Warning: this post has a slight rant tone to it.)


Let us consider three versions of read-file-into-string, a Common Lisp utility function adapted from the Alexandria source code. The questions are: How are they different? How do they work? What do they say about the code that is executed?

;;; Version A

(defun read-file-into-string (pathname &key (buffer-size 4096) external-format)
  (flet ((read-stream-content-into-string (stream)
           (check-type buffer-size (integer 1))
           (let ((*print-pretty* nil)
                 (buffer (make-array buffer-size :element-type 'character)))
             (with-output-to-string (datum)
               (loop :for bytes-read := (read-sequence buffer stream)
                     :do (write-sequence buffer datum :start 0 :end bytes-read)
                     :while (= bytes-read buffer-size))))))
    (with-open-file (stream pathname :direction :input
                                     :external-format external-format)
      (read-stream-content-into-string stream :buffer-size buffer-size))))
;;; Version B

(defun read-file-into-string ((pathname &key (buffer-size 4096) external-format)))
  (flet (read-stream-content-into-string (stream)
          (check-type buffer-size (integer 1)
          (let ((*print-pretty* nil))
                (buffer (make-array buffer-size :element-type 'character))
            (with-output-to-string (datum)))
              (loop :for bytes-read := (read-sequence buffer stream)
                    :do (write-sequence buffer datum :start 0 :end bytes-read))
                    :while (= bytes-read buffer-size)))
    (with-open-file ((stream pathname :direction :input
                                      :external-format external-format)))
      (read-stream-content-into-string stream :buffer-size buffer-size)))))))
;;; Version C

(defun read-file-into-string (pathname &key (buffer-size 4096) external-format)
  (flet ((read-stream-content-into-string (stream)
           (check-type buffer-size (integer 1))
    (let ((*print-pretty* nil)
      (buffer (make-array buffer-size :element-type 'character)))
      (with-output-to-string (datum)
        (loop :for bytes-read := (read-sequence buffer stream)
              :do (write-sequence buffer datum :start 0 :end bytes-read)
              :while (= bytes-read buffer-size))))))
        (with-open-file (stream pathname :direction :input
                                         :external-format external-format)
          (read-stream-content-into-string stream :buffer-size buffer-size))))

You are free to check these in a Common Lisp REPL in case of doubts.


The answer is that A and B tell the same story to the programmer, even though B won't compile. Many starting and ending parentheses in version B have been removed, duplicated, or displaced, which makes that code incomprehensible to the Lisp compiler.

C, however, does compile and work just like A does, and the Lisp compiler will not see any difference between forms from A and C. This is because C is a copy of A with broken indentation. The only thing that differs is the whitespace at the begining of each line.

To a Lisp programmer, version C is much more dangerous than B: while trying to evaluate the code from version B provides immediate feedback (it won't compile, it's broken code!), version C will instead silently work in a way that is not expected.


The intent conveyed by version A is that most of the space is taken by a local function, which is why most of the middle is indented more heavily than the bottom lines that form the actual body of read-file-into-string. Version C instead assumes that the only thing done by the local function is a check-type assertion - it is the only form indented in a way that denotes the body of a local function. The rest of function body implies that we first call some function named buffer on a freshly created array. Then, we open a with-output-to-string context, and perform everything else - which are the loop iteration and the subsequent with-open-file form - inside that context.

Such indentation is actively hostile towards the programmer, as I have intentionally created it to be misleading; it is therefore unlikely to find it in Lisp code that is actively used. Still, it is a proof of concept that it is possible to mislead a Lisp programmer, either by someone who either actively tries to do it or by one who is novice enough to not know better - and therefore, indirectly, a proof that indentation pays a crucial role in understanding and parsing Lisp code by humans.


To make another proof, we can take this example in another direction, a very extreme one this time. We will take the code from version A and remove all the parentheses from it (except where they are required to parse the context), leaving only indenation in place.

;;; Version D

defun read-file-into-string pathname &key (buffer-size 4096) external-format
  flet read-stream-content-into-string stream
         check-type buffer-size integer 1
         let *print-pretty* nil
             buffer make-array buffer-size :element-type 'character
           with-output-to-string datum
             loop :for bytes-read := read-sequence buffer stream
                  :do write-sequence buffer datum :start 0 :end bytes-read
                  :while = bytes-read buffer-size
    with-open-file stream pathname :direction :input
                                   :external-format external-format
      read-stream-content-into-string stream :buffer-size buffer-size

Suddenly, we get something strangely pythonesque. Code scopes are no longer defined by parentheses and instead they are defined purely by whitespace. Lisp programmers might also be put off by the sudden lack of parentheses.

And yet, this example - at least to me - reads very similar to the Lisp code from variant A. Again, this is because the indentation for both pieces of code is identical: it is clear where a given block or subblock goes deeper, where it continues at the same depth, and where it ends, and this is the information that a Lisp programmer uses when parsing code meant for human consumption.


There's a valid point that needs to be taken into account here - that one needs to be somewhat proficient Lisp semantics in order to know the argument counts for each form that is executed. In the above example, one needs to know that make-array takes one mandatory argument and may then take a number of keyword arguments, that write-sequence takes two mandatory arguments and keyword args, that check-type takes a variable and a type, and so on. Such knowledge comes only from using the language in depth, but, thankfully, it is knowledge that relates to the right side of each line of such program, rather than to the left part. And the left is where the indentation is.


When writing Lisp, two tasks are not meant to be done by humans: managing parentheses and indenting code. The programmer's focus should be on what happens between the parentheses and whose meaning and order is provided by indentation.

  • When I write Lisp, I do not pay any attention about the indentation; emacs automatically indents my code for me as I write it thanks to electric-indent and aggressive-indent.
  • When I write Lisp, I do not need to pay any attention to closing or counting parentheses: emacs automatically inserts them in pairs and prevents me from deleting a lone paren thanks to smartparens, and I have a visual color cue that informs me about the depth of a given paren thanks to rainbow-delimiters.
  • When I write Lisp, I do not need to pay much attention to where exactly I insert a new subform: if I misplace a form within my Lisp expression, emacs will automatically indent it for me, and I will notice that it is not indented at the level where I expected it to be. I can then fix its position, again, thanks to smartparens.

This is also why I consider writing Lisp code to be almost impossible without support from an editor that performs these tasks for the programmer. Even more, I consider sharing Lisp code to be impossible if that code is not formatted correctly, because then this code will not be indented correctly and will therefore either require other Lisp programmers who read it to put extra cognitive load to try and understand it, or, worse - it will give them outright wrong and misleading information about what a given piece of Lisp code does.


Oh, and while we're at it, Lisp also solves the tabs-versus-spaces debate. It is impossible to indent Lisp with tabs only, unless either tabs are exactly one-space wide or one chooses the worst possible option of both at the same time in the same lines.

So, spaces it is.

  • chevron_right

    Lisp Koans 2.0

    Michał "phoe" Herda · Saturday, 9 May - 18:04 edit

#CommonLisp #Lisp

I have rewritten the Common Lisp Koans to fix the many issues that sort-of plagued the code.

You can see, inspect, and download the outcome here.

  • chevron_right

    Common Lisp: TRIVIAL-CUSTOM-DEBUGGER

    Michał "phoe" Herda · Wednesday, 15 April - 20:19

#Lisp #CommonLisp

I have managed to create a portability library that successfully overrides the standard Lisp debugger and allows the programmer to supply their own code in its stead.

Purpose: a basic building block that allows one to implement a portable, custom debugger for Common Lisp systems in place of the original system-provided one.

Roughly tested on SBCL, CCL, ECL, Clasp, CLISP, ABCL, LW, and ACL.

TRIVIAL-CUSTOM-DEBUGGER> (with-debugger ((lambda (condition hook)
                                           (declare (ignore hook))
                                           (format t ";; Debugging a ~S!~%" 
                                                   (type-of condition))
                                           (throw :handled t)))
                           (list (catch :handled (error 'error))
                                 (catch :handled (break))
                                 (let ((*break-on-signals* 'error))
                                   (catch :handled (signal 'error)))
                                 (catch :handled 
                                   (invoke-debugger (make-condition 'error)))))
;; Debugging a ERROR!
;; Debugging a SIMPLE-CONDITION!
;; Debugging a SIMPLE-CONDITION!
;; Debugging a ERROR!
(T T T T)

See it on GitHub.

  • chevron_right

    Common Lisp: downcase Lisp files

    Michał "phoe" Herda · Wednesday, 15 April - 20:15 edit

#Lisp #CommonLisp

If you ever encounter a Lisp file that is written with upcased symbols, you might want to be able to easily convert it to downcase. That's my implementation of that.

(defun case-lisp-file (pathname case-function)
  (with-input-from-file (input pathname)
    (with-output-to-string (output)
      (loop for char = (read-char input nil nil)
            while char
            do (case char
                 (#\#
                  (princ char output)
                  (let ((next-char (read-char input)))
                    (case next-char
                      (#\\
                       (princ next-char output)
                       (princ (read-char input) output))
                      (t (unread-char next-char input)))))
                 (#\;
                  (unread-char char input)
                  (princ (read-line input) output)
                  (terpri output))
                 ((#\" #\|)
                  (unread-char char input)
                  (prin1 (read input) output))
                 (t (write-char (funcall case-function char) output)))))))

(defun upcase-lisp-file (pathname)
  "Upcases a Common Lisp source file."
  (case-lisp-file pathname #'char-upcase))

(defun downcase-lisp-file (pathname)
  "Downcases a Common Lisp source file."
  (case-lisp-file pathname #'char-downcase))

Thanks to Rainer Joswig and to travv0 for noticing and implementing fixes for that.

  • chevron_right

    Brackets in Lisp

    Michał "phoe" Herda · Sunday, 28 April, 2019 - 08:41 edit

#CommonLisp #Lisp

(set-macro-character #\[
  (lambda (stream char)
    (declare (ignore char))
    (read-delimited-list #\] stream t)))

(set-macro-character #\]
  (lambda (stream char)
    (declare (ignore stream char))
    (error "unmatched bracket on input")))
CL-USER> [defun frobnicate [foo bar]
           [list [+ foo bar] [- foo bar]
                 [* foo bar] [/ foo bar]]]
FROBNICATE
CL-USER> [frobnicate 42 20]
(62 22 840 21/10)
  • chevron_right

    The case against IF-LET*

    Michał "phoe" Herda · Monday, 15 April, 2019 - 11:49 edit · 1 minute

#CommonLisp #Lisp #Alexandria

Someone asked a question on #lisp on Freenode: since WHEN-LET has an analogous WHEN-LET*, why IF-LET has no analogous IF-LET*?

Here is my attempt at answering it.


Suppose we have a following code block:

(if-let ((x 42) 
         (y nil)
         (z :foo))
  (list :true x y z)
  (list :false x y z))

All of X, Y, and Z are bound to the respective values: 42, NIL, and :FOO. At least one of the values is false. Therefore, it should be obvious that the result of evaluating this code would be the list (:FALSE 42 NIL :FOO).

Now, let us slightly modify this code:

(if-let* ((x 42) 
          (y nil)
          (z :foo))
  (list :true x y z)
  (list :false x y z))

We no longer use IF-LET but instead we use the hypothetical sequential version, IF-LET*. We evaluate X and Y. By definition, we are supposed to not evaluate the following variables at this moment, since Y evaluated to false, and we instead execute the false branch.

The big question is: what is the value of Z in the false branch?

It is certainly not :FOO because we have not managed to evaluate that binding yet. In fact, that lexical variable should be unbound since there is no logical value for it, but there is no such thing as an unbound lexical variable in Lisp. In particular, this might mean that we encounter any number of logically unbound variables in the false branch. We could work around it by setting the not-yet-bound lexical variables to some predefined value (which would greatly complicate the code and introduce a lot of mess) or we would make the false branch unable to use any of the lexical bindings, which makes the sequential IF-LET* greatly inconsistent with the parallel IF-LET.


In other words: having IF-LET* would be inconsistent. None of the variables are available in the lexical scope of the false branch, and that should be part of IF-LET*'s contract.

  • chevron_right

    Response to One Year as Common Lisp Developer - The Bad

    Michał "phoe" Herda · Saturday, 9 February, 2019 - 07:43 · 3 minutes

In the Reddit comments of this thread, I have made a comment that turned out to be surprisingly long and off-topic - it didn't answer that particular question related to the linked article, it replied to the article as a whole. Hence I've decided to turn it into a whole separate blogpost.


This article has some points that make no sense to me.

Things in CL, even the nicer ones, can come back to bite you big time. And if you get cocky, expect a lot of pain.

That argument is meaningless. Substitute CL with any other programming language and the meaning stays the same.

As mentioned in my previous post, all the Lisp I wrote was using the Franz AllegroCL compiler

Most CL compilers come with default optimization settings that are safe, and if you abuse those, be ready for the pain.

"I used only a single implementation" clashes with "most implementations can screw you up with invalid proclamations".

You can have the most optimized and safe code available, and then you include a new dependency into your project that perhaps does some fancy optimization and then suddenly your app catches fire like no other.

"A new dependency that does some fancy optimization", to me, means that that particular dependency has unsafe code. This should nonetheless be visible in the stacktrace of any errors that happen, and if it doesn't, then the modularity of your code that calls that dependency needs to be fixed.

and if you get too cocky, you’ll pay the price

Just a stylistic remark, but the author could have used this and the related phrases about five times less, and the text would be a little bit less pretentious.


On the other hand, the arguments about using lists everywhere, dirty Lisp images, lack of a Lisp "community", small number of programmers, and people flocking to other languages, sound quite valid for me.

Using lists that aren't alists or plists is very easy for quickly hacking things together, but the lack of structure comes to bite the programmer later.

Dirty Lisp images are an issue and they have given me countless times where the code I've pushed didn't build in the first place. It forced me to learn to frequently reload the image during development, especially before pushing, and to ensure that the code loads from a clean Lisp image.

Lispers are not only scarce, they are fragmented, just like their libraries. There exist many JSON libraries, each of them being used by other programs; the same thing happens with other libraries (UIOP vs CL-FAD vs PATHNAME-UTILS, to name one).

Lots of other languages have taken features from Lisps to the point where they're "Lisps without the S-expressions". Paul Graham's original points are a sign of that: nowadays, only point 8 is unavailable in Rubies/Perls/Pythons, and point 9 is theoretically available, even though it's hard to make use of it during compile-time, since access a particular program's syntax during compilation time is nowhere as trivial as it is in Lisp.

To quote Ron Garret from his pretty great article:

I noticed that all around me people were writing code using C++ and Java and Python and even (gasp!) Perl, and they were actually getting it to work without tearing their hair out. In fact, in a number of cases I saw people whip things up in Perl in a couple of hours that would have taken me days or weeks to do in Lisp.

The conclusion was inescapable: the problem wasn't Perl or C++ or Java, it was me. I just wasn't a very good programmer any more. Lisp's power had made me complacent, and the world had passed me by. Looking back, I actually don't think I was ever a very good programmer. I just happened to have the good fortune to recognize a good thing when I saw it, and used the resulting leverage to build a successful career. But I credit much of my success to the people who designed Common Lisp.