一:结构体的构造
A structure can be considered as a deluxe(豪华版) kind of vector.
we use defstruct .we just give the name of the structure and the names of the fields。
CL-USER> (defstruct point
x
y)
POINT
CL-USER> (vector 1 2 3) #(1 2 3)
CL-USER> (setf p (make-point :x 0 :y 0)) #S(POINT :X 0 :Y 0) ;;注意对比他跟vector显示时的不一样
二:结构化对象定义后自动赋予的隐含函数
This defines a point to be a structure with two fields, x and y. It also implicitly defines the functions make-point, point-p, copy-point, point-x, and point-y.First we should call make-point to create a new point, then we can specify the values of individual fields by giving the corresponding keyword arguments.
CL-USER> (setf p (make-point :x 0 :y 0)) #S(POINT :X 0 :Y 0)
CL-USER> (point-x p) 0
CL-USER> (setf (point-y p) 2) 2
CL-USER> p #S(POINT :X 0 :Y 2)
CL-USER> p #S(POINT :X 0 :Y 2)
structure对象显示的话都是以#s开头,它是由对象中的关键字:print-function来决定的,注意下面有个例子就是通过改变:print-function 指向的函数对象然后实现structure的特定化输出
Defining a structure also defines a type of that name.using point-p to test whether something is a point,
CL-USER> (point-p p) T
CL-USER> (typep p 'point) T
给field赋予默认值
We can specify default values for structure fields by enclosing the field name and a default expression in a list in the original definition.
CL-USER> (defstruct polemic
(type (progn
(format t "What kind of polemic was it? ")
(read)))
(effect nil))
POLEMIC
CL-USER> (make-polemic)
What kind of polemic was it? string
#S(POLEMIC :TYPE STRING :EFFECT NIL) ;;注意一个structure的显示格式。
更改调用隐含函数的方式及对象的显示格式
:conc-name用于决定field前面跟什么名字来访问该field,默认情况是structure name-
:print-function 改变结构体显示时的方式,默认是#s(),他接受3个参数,一个是structure name 第二个是输出流,第三个可忽略。
CL-USER> (defstruct (point (:conc-name p)
(:print-function print-point))
(x 0)
(y 0))
POINT
CL-USER> (defun print-point (p stream depth)
(format stream "#<~A,~A>" (px p) (py p)))
PRINT-POINT
CL-USER> (setf pp (make-point)) #<0,0> ;;输出格式按照上面我们重新定义的,而不是#s(point :x 0 :y 0)
CL-USER> (px pp) 0 ;;不需要用point-x来访问该域的值了
如果:conc-name nil的话,就是不需要用前缀,直接用域名就可以作为函数后面跟structure对象名字就可以实现对该域的访问
CL-USER> (setf oo (make-point)) #<0,0>
CL-USER> (x oo) 0