[英]Not-rectangular arrays in Common Lisp? (General question for didactical purposes.)
Simply for the sake of completeness I would like to know, whether there is a way to define "jagged" or "ragged arrays" in Common Lisp like it is described for Java eg here: https://www.geeksforgeeks.org/jagged-array-in-java/只是为了完整起见,我想知道是否有一种方法可以在 Common Lisp 中定义“锯齿状”或“参差不齐的数组”,就像在 Java 中描述的那样,例如: https://www.geeksforgeeks.org/jagged -array-in-java/
Along with this question comes the second question, what is the advantage of such a definition of multidimensional arrays?伴随这个问题而来的是第二个问题,这样定义多维arrays有什么好处? More efficient memory allocation?
memory配置效率更高? Or is the idea of a "jagged array" itself problematic - at least in the Common Lisp context?
或者“锯齿状数组”的想法本身有问题——至少在 Common Lisp 上下文中?
Until now, I only could find descriptions of the regular way of defining rectangular multidimensional arrays - or I overlooked the information I was searching for.直到现在,我只能找到定义矩形多维 arrays 的常规方法的描述 - 或者我忽略了我正在搜索的信息。
At this moment, I would imagine that in Common Lisp one would fill the not needed places with NIL or 0 or something like that in a regular multidimensional array, if the replication of such an asymmetric data field seems to be useful.此时此刻,我会想象在 Common Lisp 中,如果这种非对称数据字段的复制似乎有用,人们会在常规多维数组中用 NIL 或 0 或类似的东西填充不需要的地方。 ... Or I would manage three vectors of different length maybe by trying to define a custom structure with them.
...或者我会管理三个不同长度的向量,可能会尝试用它们定义一个自定义结构。
If these are stupid ideas, is there any other way?如果这些都是愚蠢的想法,还有其他办法吗? Or is a "ragged array" in Java simply a nested vector with elements of different size in general - and a multidimensional array in Common Lisp also simply a nested vector with elements of equal size that comes along with some helpful abstractions for managing that regular structure?
或者是 Java 中的“参差不齐的数组”,通常只是一个具有不同大小元素的嵌套向量 - 而 Common Lisp 中的多维数组也只是一个具有相同大小元素的嵌套向量,并带有一些有用的抽象来管理该常规结构?
I thank you very much for your response.非常感谢您的回复。
Since they are vectors of vectors they are easy to define.因为它们是向量的向量,所以很容易定义。 Example:
例子:
getter吸气剂
(defun jref (jarray i j)
(aref (aref jarray i) j))
setter二传手
(defun (setf jref) (new-value jarray i j)
(setf (aref (aref jarray i) j) new-value))
Make such an array: (make-jarray '(3 (5 6 2))
制作这样一个数组:
(make-jarray '(3 (5 6 2))
(defun make-jarray (dimensions &key (initial-element 0))
(make-array
(first dimensions)
:initial-contents (loop for d in (second dimensions)
collect (make-array
d
:initial-element initial-element))))
Example:例子:
CL-USER > (let ((ja1 (make-jarray '(4 (3 2 4 5)))))
(setf (jref ja1 0 1) 'hello)
(setf (jref ja1 3 4) 'world)
(incf (jref ja1 2 0) 42)
(values ja1
(jref ja1 2 0)))
#(#(0 HELLO 0) #(0 0) #(42 0 0 0) #(0 0 0 0 WORLD))
42
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.