Lisp Structures |
|
Defstruct allows you to create your own data structures and automatically produces functions for accessing the data. Structures have names and ``slots.'' The slots are used for storing specific values. Defstruct creates a generic type of which particular ``instances'' can be made. Here is a comparison of LISP's defstruct and C's struct. One difficulty with structures are the dashes. Almost all of their variable names use dashes, but dashes are also part of the syntax for accessing structure fields (or structure elements as they're called in C). As you read, be sure to notice what dashes are part of variable names and which ones are operators. Generally structures in LISP are a lot like structures in C. |
|
Lisp | C / C++ |
(defstruct <structure name> (<field name> <default value>) (<field name> <default value>) (<field name> <default value>) ) |
typedef struct{ <type> <field name> <default value> ; <type> <field name> <default value> ; <type> <field name> <default value> ; } <structure name> ; |
Examples | |
>(defstruct student (gender) (age) (first_name nil) (last_name nil) (grade_level 11)) |
typedef struct { int Gender; int Age; int First_Name; int Last_Name; int grade_level; }Student; |
In this example "student" is the name of the structure and gender, age, first_name, last_name and grade_level are the slots. In the sample the slots are given default values such as nil for first_name and 11 for grade_level "nice". The default values are enclosed in parentheses with the slot name.) It is not required that slots be given default values. Defstruct creates a constructor, a reader, a writer, and a predicate to test if a variable is a particular structure. Remember, like a structure in C, defstruct does not create an instance of a structure, it only sets up the data type for memory, etc. To create an instance, use a constructor. | |
ReaderEach slot is provided an automatic access function, by joining the structure name with the slot name: To access data stored in a field of a structure: (<structure name> - <field name> <instance>) Example: >(student-gender sn170345) female >(student-grade_level sn170345) 11 >(student-age sn170345) 16 |
|
  |   |