Next: Creating Subtypes Up: Structures Previous: Structures

# Creating Structure Types

A new structure type is created with one of two `struct` forms: ``

      (struct s (field   ))
      (struct (s t-expr) (field   ))

where s and each field are identifiers. The latter form is described in section 5.2.

A `struct` expression with n fields returns 3+2n values:

- `struct:` s, a structure type descriptor value that represents the new datatype. The purpose of this value is explained in section 5.2.
- `make-`s, a constructor procedure that takes n arguments and returns a new structure value.
- s`?`, a predicate procedure that returns `#t` for a value constructed by `make-`s (or the constructor for a subtype; see section 5.2) and `#f` for any other value.
- s`-`field, for each field, a selector procedure that takes a structure value and extracts the value for field.
- `set-`s`-`field`!`, for each field, a setter procedure that takes a structure and a new field value. The field value in the structure is destructively updated with the new value, and void is returned.

The order of the return values from a `struct` expression is the same as in the list above, up and including to the setter procedure for the first field (if the structure type has any fields). If the structure type has more than one field, the selector for the second field is next, followed by the setter for the second field, and so on for additional fields.

The names `make-`s, etc. are only used by the return values of `struct` for error-reporting. But these names are used as binding variables by the `define-struct` and `let-struct` macros: ``

      (define-struct s (field   ))

      (define-values (struct:s make-s s? s-field set-s-field!   ) (struct s (field   )))

`

      (let-struct s (field   )
         body-expr   )

      (let-values ([(struct:s make-s s? s-field set-s-field!   ) (struct s (field   ))])
         body-expr   )

`

Each time a `struct` expression is evaluated, a new structure type is created with distinct constructor, predicate, selector, and setter procedures. If the same `struct` expression is evaluated twice, instances created by the constructor returned by the first evaluation will answer `#f` to the predicate returned by the second evaluation.

Examples: ``

      (define-struct cons-cell (car cdr))
      (define x (make-cons-cell 1 2))
      (cons-cell? x) ; => #t
      (cons-cell-car x) ; => 1
      (set-cons-cell-car! x 5)
      (cons-cell-car x) ; => 5

      (define orig-cons-cell? cons-cell?)
      (define-struct cons-cell (car cdr))
      (define y (make-cons-cell 1 2))
      (cons-cell? y) ; => #t
      (cons-cell? x) ; => #f, cons-cell? now checks for a different type
      (orig-cons-cell? x) ; => #t
      (orig-cons-cell? y) ; => #f

Next: Creating Subtypes Up: Structures Previous: Structures