Skip to content

Instantly share code, notes, and snippets.

@linktohack
Created February 10, 2023 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linktohack/82003155c14162de46344f943b2d911d to your computer and use it in GitHub Desktop.
Save linktohack/82003155c14162de46344f943b2d911d to your computer and use it in GitHub Desktop.
Elisp merge lists, keep order
(defun merge-lists (&rest lists)
"Merge list, keep elements' order the same as where they are in the original lists.
E.g `(merge-list '(1 2) '(3 4 5))' should returns `(1 3 2 4 5)'."
(let ((copy (mapcar 'copy-sequence lists))
(result))
(while copy
(dolist (lst copy)
(when-let ((elt (pop lst))) ; pop doesn't change `lst'
(push elt result)))
(setq copy (remove nil copy)))
(nreverse result)))
(defun merge-lists (&rest lists)
"Merge list, keep elements' order the same as where they are in the original lists.
E.g `(merge-list '(1 2) '(3 4 5))' should returns `(1 3 2 4 5)'."
(let ((copy (mapcar 'copy-sequence lists))
(result))
(while copy
(dolist (lst copy)
(pcase lst
(`(,a ,b . ,rest) (progn
(push a result)
(setcar lst b)
(setcdr lst rest)))
(`(,a) (progn
(push a result)
(setcar lst nil)
(setcar lst nil)))))
(setq copy (remove '(nil) (remove nil copy))))
(nreverse result)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment