Lisp - Structure Types
In LISP, we can define basic structures using defstruct. In this chapter, we'll check features of structure types in details.
Basic Structures with defstruct
defstruct is a macro to create a simple structure with named slots. The new data type is created with automatically generated constructor and accessor functions.
Example - Create a Structure
main.lisp
; define a structure book (defstruct book title author subject id ) ; create book using make-book constructor and assign a structure to book1 ( setq book1 (make-book :title "C Programming" :author "Nuha Ali" :subject "C-Programming Tutorial" :id "478") ) ; get values from book1 using automatic accessors (print(book-title book1)) (terpri) (print(book-author book1)) (terpri) (print(book-subject book1)) (terpri) (print(book-id book1))
Output
When you execute the code, it returns the following result −
"C Programming" "Nuha Ali" "C-Programming Tutorial" "478"
Key Features of LISP Structure
Using defstruct, we can create a new data type.
Accessor functions are generated automatically to access named slots.
Constructor is generated automatically to create new instance.
By this way, structure provides a basic data aggregation.
Limitations of LISP Structure
A LISP Structure is simple as compared to full fledged CLOS (Common LISP Object System) object oriented data types.
LISP Structure inheritance capability is limited. Only single inheritance is supported as compared to CLOS multiple inheritance. A LISP Structure inheritance is limited to inheriting the slots of included structure.
Conclusion
A LISP Structure is good for simple data grouping. We can use dynamic type checking of LISP to check types of structure making it suitable for custom data types.