[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Help with recursive destructive function

From: Michael Heerdegen
Subject: Re: Help with recursive destructive function
Date: Thu, 10 May 2018 03:52:07 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux)

Eric Abrahamsen <address@hidden> writes:

> These are the sorts of things I can typically handle (sometimes even
> without bugs!), whereas Clement's (or your, or Stefan's) function
> isn't...

I tweaked it a bit and extended the idea for arrays.  Hope the comments
are helpful.  Uses seq.el and cl-lib.

#+begin_src emacs-lisp
;; -*- lexical-binding: t -*-

(defun deep-edit (edit-fun data)
  ;; DATA is the structure to process.
  ;; EDIT-FUN is a function accepting one argument THING that returns
  ;; non-nil when THING is something to be replaced.  The non-nil
  ;; return value should be a function that when called with the THING as
  ;; argument returns the replacement for THING.
  ;; Example: (lambda (thing) (and (stringp thing) #'upcase)) as
  ;; EDIT-FUN would cause all strings being replaced with their upcased
  ;; version.
  (let ((stack `((identity ignore ,data))))
    (while stack
      (pcase-let* ((`(,getter ,setter ,cell) (pop stack))
                   (current                  (funcall getter cell))
                   (modify-fun               (funcall edit-fun current)))
         ;; 1. When we should replace CURRENT, do it
          (funcall setter cell (funcall modify-fun current)))
         ;; FIXME: Do hash-tables fit here?

         ;; 2. Check whether we need to traverse CURRENT
         ((consp current)
          (cl-callf2 append
              `((car setcar ,current)
                (cdr setcdr ,current))
         ((and (arrayp current) (not (stringp current)))
          (cl-callf2 append
              (let ((i -1))
                 (lambda (_)
                   (let ((j (cl-incf i)))
                     `(,(lambda (x)   (aref x j))
                       ,(lambda (x v) (aset x j v))

;; Example to try:
(let ((tree '("a" "b" "c"
              (2 ("d" . 3))
              (4 . "e")
              (("g" . "h")
               (["i" "j"
                 ("k" "l")
   (lambda (thing) (and (stringp thing) #'upcase))


reply via email to

[Prev in Thread] Current Thread [Next in Thread]