LISP - Structures


Advertisements

Structures are one of the user-defined data type, which allows you to combine data items of different kinds.

Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −

  • Title
  • Author
  • Subject
  • Book ID

Defining a Structure

The defstruct macro in LISP allows you to define an abstract record structure. The defstruct statement defines a new data type, with more than one member for your program.

To discuss the format of the defstruct macro, let us write the definition of the Book structure. We could define the book structure as −

(defstruct book 
   title 
   author 
   subject 
   book-id 
)

Please note

  • The above declaration creates a book structure with four named components. So every book created will be an object of this structure.

  • It defines four functions named book-title, book-author, book-subject and book-book-id, which will take one argument, a book structure, and will return the fields title, author, subject and book-id of the book object. These functions are called the access functions.

  • The symbol book becomes a data type and you can check it using the typep predicate.

  • There will also be an implicit function named book-p, which is a predicate and will be true if its argument is a book and is false otherwise.

  • Another implicit function named make-book will be created, which is a constructor, which, when invoked, will create a data structure with four components, suitable for use with the access functions.

  • The #S syntax refers to a structure, and you can use it to read or print instances of a book.

  • An implicit function named copy-book of one argument is also defined that. It takes a book object and creates another book object, which is a copy of the first one. This function is called the copier function.

  • You can use setf to alter the components of a book, for example

(setf (book-book-id book3) 100)

Example

Create a new source code file named main.lisp and type the following code in it.

(defstruct book 
   title 
   author 
   subject 
   book-id 
)

( setq book1 (make-book :title "C Programming"
   :author "Nuha Ali" 
   :subject "C-Programming Tutorial"
   :book-id "478")
)

( setq book2 (make-book :title "Telecom Billing"
   :author "Zara Ali" 
   :subject "C-Programming Tutorial"
   :book-id "501")
) 

(write book1)
(terpri)
(write book2)
(setq book3( copy-book book1))
(setf (book-book-id book3) 100) 
(terpri)
(write book3)

When you execute the code, it returns the following result −

#S(BOOK :TITLE "C Programming" :AUTHOR "Nuha Ali" :SUBJECT "C-Programming Tutorial" :BOOK-ID "478")
#S(BOOK :TITLE "Telecom Billing" :AUTHOR "Zara Ali" :SUBJECT "C-Programming Tutorial" :BOOK-ID "501")
#S(BOOK :TITLE "C Programming" :AUTHOR "Nuha Ali" :SUBJECT "C-Programming Tutorial" :BOOK-ID 100)
Advertisements