如何在 Common Lisp 中复制数组?
我想复制我的二维数组,这感觉是处理数组的一种很好的、实用的、非破坏性的方式。这样做的 lispy 方式是什么?
I'd like to make copies of my 2D array, which feels like the nice, functional, nondestructive way of handling arrays. What is the lispy way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更新:如今,alexandria 有一个
副本- array
与下面给出的实现非常相似。用那个。过时的答案:我使用了以下内容,我认为它比当时的 alexandria 版本更好:
alexandria 版本的问题是
adjust-array
hack 导致结果(至少在 SBCL 上)永远不会是
simple-array
,这是其他一些库(例如opticl)所期望的。这上面的版本对我来说也更快。
其他人在不同的地方发布了非常相似的版本
图书馆,但我忘记了人和图书馆的名字。
UPDATE: Nowadays, alexandria has a
copy-array
very similar to the implementation given below. Use that.OBSOLETE ANSWER: I used the following, which I believed was better than the alexandria version at the time:
The problem with the alexandria version was that the
adjust-array
hack causes the result (at least on SBCL) to never be a
simple-array
, which some other libraries (e.g. opticl) expect. Theabove version also was faster for me.
Someone else has published a very similar version in a different
library, but I forgot the names of both person and library.
Common Lisp 库 Alexandria (可通过 quicklisp) 包含任意等级和维度的
copy-array
实现:The Common Lisp library Alexandria (installable through quicklisp) includes an implementation of
copy-array
for arbitrary ranks and dimensions:这取决于你的 2D 数组如何表示,以及你使用什么风格的 Lisp。
如果您使用的是 Common Lisp,则 copy-seq可能有用。
It depends how your 2D array is represented, and what flavor of Lisp are you using.
If you are using Common Lisp, then copy-seq could be useful.
如果您想要
以良好的、实用的、非破坏性的方式做事
,那么您为什么还需要复制它呢?如果您复制它是为了更新它——那么您就没有按照功能方式进行操作。
如果您以功能方式执行此操作 - 那么您不需要副本。您可以将其传递到任何地方。
也许你想改变它。在这种情况下,您可以使用 Lisp 的众多纯函数之一,例如
mapcar
或filter
。If you want to do things
the nice, functional, nondestructive way
, then why do you even need to copy it?if you're copying it in order to update it -- then you're not doing it the functional way.
if you're doing it the functional way -- then you don't need a copy. You can just pass it anywhere and everywhere.
Maybe you want to transform it. In that case, you could use one of Lisp's many pure functions, such as
mapcar
orfilter
.