[previous] [up] [next]     [contents] [index]
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  tex2html_wrap_inline12550 ))
  (struct (s t-expr) (field  tex2html_wrap_inline12550 )) 
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:

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  tex2html_wrap_inline12550 )) 
   tex2html_wrap_inline12616 
  (define-values (struct:s make-s s? s-field set-s-field!  tex2html_wrap_inline12550 ) (struct s (field  tex2html_wrap_inline12550 ))) 
  (let-struct s (field  tex2html_wrap_inline12550 )
     body-expr  tex2html_wrap_inline12552 ) 
   tex2html_wrap_inline12616 
  (let-values ([(struct:s make-s s? s-field set-s-field!  tex2html_wrap_inline12550 ) (struct s (field  tex2html_wrap_inline12550 ))])
     body-expr  tex2html_wrap_inline12552 ) 

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 constuctor 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-car x) ; => 1
  (set-cons-car! x 5) 
  (cons-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


[previous] [up] [next]     [contents] [index]
Next: Creating Subtypes Up: Structures Previous: Structures

PLT