reddit / emacs

Circular list error

teckau22 · 2022-12-21 20:53
Consider the following small example: (setq teckau22/mylist '((:field1 "f1A" :field2 "f2A") (:field1 "f1B" :field2 "f2B") (:field1 "f1C" :field2 "f2C"))) (defun teckau22/myfunction (f1 f2list) (if t `(,f1 ,f2list) '("default_f1" ("default_f2list")))) (mapcan (lambda (arg) (teckau22/myfunction (plist-get arg :field1) `(,(plist-get arg :field2)))) teckau22/mylist) Evaluating `mapcan` results in `("f1A" ("f2A") "f1B" ("f2B") "f1C" ("f2C"))`, as expected. But replacing `if t` with `if nil` in `teckau22/myfunction`, I would expect the output to be `("default_f1" ("default_f2list") "default_f1" ("default_f2list") "default_f1" ("default_f2list"))`. However I get a circular list error. I have two questions: 1. Both outputs of `teckau22/myfunction` are of the form (string (string)), so why do I get an error when the default values are chosen (i.e., when I have `if nil` instead of `if t`)? 2. How can I get the desired output for the default values? (`("default_f1" ("default_f2list") "default_f1" ("default_f2list") "default_f1" ("default_f2list"))`)
nv-elisp · 2022-12-21 20:57
You're writing self-modifiying code by using a quoted list in the defun. This comes up all the time: https://emacs.stackexchange.com/questions/45820/when-to-use-quote-for-lists-modifying-quoted-lists-in-elisp Note the use of the `list` function, rather than using quoted lists in the function definition: (require 'cl-macs) (cl-flet ((modlist (f1 f2list toggle) (if toggle `(,f1 ,f2list) (list "default_f1" (list "default_f2list"))))) (let ((test (list (list :field1 "f1A" :field2 "f2A") (list :field1 "f1B" :field2 "f2B") (list :field1 "f1C" :field2 "f2C")))) (mapcan (lambda (arg) (modlist (plist-get arg :field1) `(,(plist-get arg :field2)) nil)) test)))
teckau22 · 2022-12-22 01:00
This makes a lot of sense, thank you very much for the reply.