DEV Community

Vee Satayamas
Vee Satayamas

Posted on

1

The worst mistake that I made in Common Lisp programming

My programs have defects because some functions destroy or mutate shared data. I avoid mutating shared data in Common Lisp; for example, I use CONS. However, I made a mistake by using SORT, which wasn't aware that SORT is destructive. Sometimes I still forget that SORT mutates its input data. The function sort-snode below sorts a part of a tree.

(defun sort-snode (snode attr)
  (flet ((key-fn (r)
       (cdr (assoc attr r))))
    (sort snode #'< :key #'key-fn)))
Enter fullscreen mode Exit fullscreen mode

Since it is based on SORT, it changes the input data, which is snode. After I found the output tree didn't look what I expected, I took days to see where my mistake was.

My workaround is running COPY-LIST before SORT, as shown below.

(defun sort-snode (snode attr)
  (flet ((key-fn (r)
       (cdr (assoc attr r))))
    (sort (copy-list snode) #'< :key #'key-fn)))
Enter fullscreen mode Exit fullscreen mode

In brief, if you are new to Common Lisp, please beware of destructive operations, which is not limited to SORT. It can be NCONC.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs