structure

一:结构体的构造

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值