How You Do Project Euler in Emacs Lisp

Upon the late summer of 2023, I finished problems I'd missed from project euler 1-100 in emacs lisp1 just before my life fell apart. I knew I'd be ok though, seeing as I would live 2000+ years into the future to write this blog post.

The two things I kept using repeatedly were

  1. edebug: step through capabilities!
    This tutorial by endlessparenthesis was helpful.

    And the manual is seriously worth reading.

  2. cl-loop: for the most expressive looping I've ever experienced in my life2.

I didn't find anyone else who published their emacs lisp solutions up to 100. But there were of course lispers who had done far more. I was definitely inspired by a few others before I started:

  • someone else had a collection of a few dozen of their solutions posted as a giant file of HTML on their blog. (They were from Mexico? I don't remember)
  • skeeto's commmon lisp solutions, and a lot were just loop macros. He might have even remarked about this on his blog.
  • I also watched an emacs youtuber, who did common lisp, talk about how they loved the loop macro so much.

Anyway, cl-loop is a super power. You can read about it in the cl-lib info manual. Once you get used to the DSL, you can rip through a lot of earlier problems! It's really performant for elisp.

Here's just a function to generate a hash table from an input list:

(defun jwow/list-to-hash-table (input-list)
  (cl-loop for (k v) in input-list
           with ht = (make-hash-table :test #'equal)
           do (puthash k v ht)
           finally return ht))

I find this more expressive and faster to grasp than using a mapping function with a lambda:

(defun yaml--alist-to-hash-table (l)
  ;; ommitted...
  (let ((h (make-hash-table)))
    (seq-map (lambda (cpair)
               (let* ((k (car cpair))
                      (v (alist-get k l)))
                 (puthash k v h)))
             l)
    h))
1

The notebook is too messy to be of easy value https://codeberg.org/MegaJ/euler-elisp. It's also not very readble unless you're opening up my notebook in org mode. Still, I consider it a major achievement! Might brush it up to make it more comprehensible some day.

2

I wonder if this article is just an ad for cl-loop, it's just so good! Maybe this should be a short series where I actually show some solutions to project euler.