Emacs — How to replace nth element of a list with a let-bound variable

强颜欢笑 提交于 2019-11-30 15:44:22

You need to use setcar and nthcdr:

(setcar (nthcdr 17 the-list) my-variable)

The more common-lisp-like approach is to use Generalized Variables:

(setf (nth 17 the-list) my-variable)

Emacs has a concept of Generalized Variables, which essentially lets you change arbitrary storage places with setf. For instance, you can change car and cdr places of list, including the car returned by nth. Hence, the following code

(let ((foo 10)
      (l '(1 2 3 4 5 6 7 8)))
  (setf (nth 4 l) foo)
  l)

will return the list (1 2 3 4 10 6 7 8).

To put variables directly into a quoted list, you must change the kind of quoting. The standard quote ' inhibits any evaluation inside the quoted expression.

The special Backquote however lets you evaluate expressions inside a quoted expression:

(let* ((foo 10)
      (l `(1 2 3 4 5 ,foo 7 foo)))
  l)

The leading comma marks the subsequent expression for evaluation, whereas expressions without a leading comma will be taken literally. In the above example, the first occurrence of foo in the list will be evaluated, and hence replace with 10, whereas the second occurrence ends up literally in the list.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!