本文介绍了通用lisp:用于defstruct结构的slot-value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在常见的Lisp中,如何使用插槽名称/符号访问结构插槽?

In common lisp, what can I use to access structure slot using slot name/symbol?

我想要的是

(defstruct point (x 0) (y 0))    
(defmacro -> (struct slot) `(slot-value ,struct ,slot))

(setf p (make-point))
(setf (slot-value p 'x) 1)
(setf (-> p 'y) 2)

我正在使用clozure cl,在clozure cl中可以使用。但是,AFIAK这是非标准行为(相当于未定义行为 C ++)。我不打算切换到其他CL实现,所以我应该对结构继续使用 slot-value 还是有更好的方法?

I'm using clozure cl, and In clozure cl this works. However, AFAIK this is non-standard behavior (equivalent to "undefined behavior" C++). I'm not planning to switch to another CL implementation, so should I keep using slot-value for structures, or is there a better way to do it?

推荐答案

通常,您将访问器函数与结构一起使用。

Usually you would use accessor functions with structures.

您的代码定义了访问器函数 point-x point-y 。您可以使用它们。

Your code defines the accessor functions point-x and point-y. You can use those.

您还可以在支持它的实现上使用 SLOT-VALUE 。我想这是大多数实施方式(GCL是一个例外)。有Lisp软件假定 SLOT-VALUE 适用于结构。我认为实施不会删除对此的支持。这不是标准,因为某些实现者不想在已部署的应用程序中提供此功能。

You can also use SLOT-VALUE with structures on implementations which support it. I guess that's most implementations (GCL would be an exception). There is Lisp software which assumes that SLOT-VALUE works for structures. I don't think implementations will remove support for it. It'a not in the standard, because some implementors wouldn't want to provide this functionality in deployed applications.

所以两种方法都可以。

如果要使用短名称,请使用访问器:

If you want to have short names, go with accessors:

CL-USER 109 > (defstruct (point :conc-name)
                (x 0) (y 0))
POINT

CL-USER 110 > (make-point :x 5 :y 3)
#S(POINT :X 5 :Y 3)

CL-USER 111 > (setf p1 *)
#S(POINT :X 5 :Y 3)

CL-USER 112 > (x p1)
5

CL-USER 113 > (setf p2 (make-point :x 2 :y 3))
#S(POINT :X 2 :Y 3)

CL-USER 114 > (list p1 p2)
(#S(POINT :X 5 :Y 3) #S(POINT :X 2 :Y 3))

CL-USER 115 > (mapcar 'x (list p1 p2))
(5 2)

名称之间发生冲突

如果要编写较短版本的 SLOT-VALUE ,也可以。写一个宏。或编写一个内联函数。当然-为什么不呢?

If you want to write a shorter version of SLOT-VALUE, that's also fine. Write a macro. Or write an inlined function. Sure - why not?

正如我所说, SLOT-VALUE 在大多数实现中都适用于结构。在这种情况下,您不必担心ANSI CL规范没有对此进行定义。实现在许多方面扩展了ANSI CL规范。例如,通过 SLOT-VALUE 处理结构,将流实现为CLOS类,将条件实现为CLOS类,提供元对象协议,...

As I said, SLOT-VALUE works with structures in most implementations. In this case you should not care that the ANSI CL spec does not define that. In many ways implementations extend the ANSI CL spec. For example by SLOT-VALUE working on structures, implementing streams as CLOS classes, implementing conditions as CLOS classes, providing a Meta-object Protocol, ...

这篇关于通用lisp:用于defstruct结构的slot-value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 20:31