Common Lisp/Reference/defstruct

From Wikibooks, open books for an open world
< Common Lisp‎ | Reference
Jump to: navigation, search

The defstruct construct declares a new user-defined data type which has a fixed number of named components. It also creates structure constructor.

Example[edit]

The following example[1] declares a Lisp structure with the symbol point and three slots referenced by the symbols x, y, and z. Here constructor is named make-point.

(defstruct point x y z) ; define structure

(defvar my-point) ; define var 

(setf my-point (make-point :x 3 :y 4 :z 12)) ;  set value of slots of var 

(point-x my-point) ; acces to slots
;; объявление и инициализация структуры (initiating of structure)
(defstruct 3dpoint (x 0) (y 0) (z 0));

;; обязательно превращем все это в динамическую переменную
(defvar *my-points* (make-array '(1000000) :element-type '3dpoint))

;; получение случайного числа  (get random number from interval)
(defun random-from-range (start end)
(+ start (random (+ 1 (- end start)))))

;; функция заполнения массива структур (set values in array of structures)
(defun setf-my-points (*my-points*)
	(declare (special *my-points*))
	(loop for i from 1 to 1000000 do
		(progn 
		      (print i)
		      (setf (aref *my-points* i) 
		      (make-3dpoint :x (random-from-range 1 100) 
				    :y (random-from-range 100 200) 
				    :z (random-from-range 300 400)))     
		)
	)
)

;; заполняем случайными значениями 1 (call function that set value in array of structures)
(print (time (setf-my-points *my-points*)))

;; получаем доступ к случайному значению (1 1000000) access to random ID record 
(3dpoint-x (aref *my-points* (random-from-range 1 1000000)))

;; смотрим время доступа... (see time)
(print (time (3dpoint-x (aref *my-points* (random-from-range 1 1000000)))))

See also[edit]

References[edit]

  1. Fundamentals of CLOS by Nick Levine, Ravenbrook Limited, 2003-07-15