How to set an element in a multi-dimensional array in elisp

梦想的初衷 提交于 2019-12-12 02:15:24

问题


I am working with someone using elisp and we have been struggling to use multi-dimensional arrays.

The problem is that if we try to set a value using

(setf (elt (elt m-array 0) 0) 5))

We end up getting something like this

[[0 0 0 5] [0 0 0 5] [0 0 0 5] [0 0 0 5]]

which is not what we want. Now Common Lisp has the support we need to get around this. Unfortunately though, we are only able to work with elisp. My question is, given that we only have elisp, how can we work around this such that we instead only set one vector in the vectors.

Like:

[[0 0 0 5] [0 0 0 0] [0 0 0 0] [0 0 0 0]]

回答1:


While Common Lisp has multidimensional arrays, Emacs Lisp has only vectors (one-dimensional arrays).

You are trying to emulate multidimensional arrays in ELisp using vectors of vectors (which is, indeed, a fairly standard trick), but you need to be careful to avoid "aliasing" - i.e., you need to make sure that your nested arrays are not identical objects.

Your problem indicates is that

(eq (aref m-array 0) (aref m-array 1))
==> t

because you probably created your m-array like this:

(setq m-array (make-vector 5 (make-vector 5)))

You need to create your m-array like this:

(setq m-array (make-vector 5 nil))
(dotimes (i 5)
  (setf (aref m-array i) (make-vector 5 0)))


来源:https://stackoverflow.com/questions/42603751/how-to-set-an-element-in-a-multi-dimensional-array-in-elisp

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