Adam Richardson's Site

Emacs Lisp Notes

Table of Contents

<2022-05-01 Sun>

Lists

Filtering a list

  • You can use the mapcar function to iterate through each item in the list
  • In the mapcar function you can perform a predicate that will turn matches into some known value that can be removed
  • The delete function can remove all instances of some value from a list
  • The delete function will mutate the list
  • The remove function will do the same but not mutate the list
  • There are also seq-filter and seq-remove in the seq.el library.
(defun ajr-filter (pred seq)
  "Return a copy of `seq' with all items that match `pred' filtered out."
  (let ((remove-val -99988844421))
    (remove remove-val
            (mapcar
             (lambda (i)
               (if (funcall pred i)
                   remove-val
                 i))
             seq))))

(setq x (list 1 2 'bbb 3 4 5 6 7 9))

(print (ajr-filter (lambda (n) (or (equal n 'bbb)
                                   (equal n 2))) x))

(print x)

(require 'seq)
(print (seq-filter (lambda (n) (not (equal n 'bbb))) x))
(print (seq-remove (lambda (n) (not (equal n 'bbb))) x))

(print x)

Strings

Contains substring predicate

  • Use string-match and a regular expression to determine if a string contains a substring
(setq x (list "file1.txt"
              ".config"
              "photo1.jpg"
              "logo.gif"
              "photo2.jpg"
              "raw.tiff"
              "file2.txt"))

(setq picture-extensions (list "jpg"
                               "gif"
                               "tiff"))

(defun ext-regexp (extensions)
  "Returns a REGEXP that matches on the `extensions'. "
  (format ".+\\.\\(%s\\)" (string-join extensions "\\|")))

(print (setq picture-regexp (ext-regexp picture-extensions)))

(require 'seq)
(print (seq-filter (lambda (s)
                     (string-match picture-regexp s))
                   x))