Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Modules and Contracts

Structs and Contracts

Define Racket structs, guard fields with contracts, use struct-out and #:transparent, immutable updates with struct-copy, and run a JavaScript record validator stand-in.

Lists are flexible, but a program that passes around "a list where element 2 is the age" is asking for bugs. Structs give your data names: a point has an x and a y, a person has a name and an age. Combined with contracts, a struct also guarantees its invariants, such as "the age is never negative", at every boundary it crosses.

This lesson covers defining structs, immutability and copying, equality and printing, contracts on structs, and a stand-in validator in JavaScript. It follows Contracts Basics.

Racket is read-only on this site. The runnable block is a JavaScript stand-in using frozen objects and a validating constructor.

Defining a struct

RACKET
#lang racket

(struct person (name age) #:transparent)

(define ada (person "Ada" 36))
(person-name ada)        ; => "Ada"
(person-age ada)         ; => 36
(person? ada)            ; => #t
(person? 42)             ; => #f
ada                      ; prints (person "Ada" 36) because of #:transparent

One struct line creates a constructor (person), a predicate (person?) and an accessor per field (person-name, person-age). Without #:transparent, printing shows only #<person> and equal? compares by identity; with it, equal? compares field by field, which is usually what you want for plain data:

RACKET
(equal? (person "Ada" 36) (person "Ada" 36))  ; => #t

Structs are immutable by default. To "change" one, you make a copy with struct-copy:

RACKET
(define older (struct-copy person ada [age 37]))
(person-age older)   ; => 37
(person-age ada)     ; => 36, the original is untouched

Add #:mutable to the struct (or to one field) only when you really need set-person-age!. Immutable data is easier to test and safe to share.

Putting contracts on structs

The cleanest way is struct-out plus per-field contracts in contract-out:

RACKET
(provide (contract-out
          [struct person ([name string?]
                          [age (and/c natural? (<=/c 150))])]))

Now any code outside the module that constructs a person with a negative age, or an age as a string, is blamed immediately. Inside the module, you can still build structs freely, so keep constructors trustworthy there.

For stronger guarantees you can hide the constructor and expose only a smart constructor that validates:

RACKET
(struct person (name age))         ; private constructor

(define (make-person name age)
  (unless (string? name) (raise-argument-error 'make-person "string?" name))
  (unless (and (natural? age) (<= age 150))
    (raise-argument-error 'make-person "natural number up to 150" age))
  (person name age))

(provide (contract-out
          [make-person (-> string? natural? person?)]
          [person-name (-> person? string?)]
          [person-age  (-> person? natural?)])
         person?)

Because person (the real constructor) is not exported, no outside code can create an invalid one: the invariant holds everywhere. person? is exported so other modules can ask whether a value is a person.

Inheritance, guards and properties

A struct can extend another: (struct student person (school)) creates a subtype with all of person's fields plus school. The #:guard option runs a check on every construction, even inside the module:

RACKET
(struct temperature (celsius)
  #:guard (lambda (c name)
            (unless (>= c -273.15)
              (error name "below absolute zero: ~a" c))
            c))

Structs can also implement generic interfaces and properties, for example prop:custom-write to control printing, or #:methods gen:equal+hash for custom equality. These let your data type plug into equal?, hash tables and sort as if it were built in.

classDiagram
  class person {
    name : string
    age : natural
  }
  class student {
    school : string
  }
  person <|-- student

student has everything person has, plus its own field.

Stand-in: records with invariants

JavaScript's Object.freeze gives immutability, and a factory function plays the part of the smart constructor. This block builds person, copies it, and shows validation:

JS Stand-in: immutable records with a validating constructor

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Hiding the constructor in Racket is stronger than this stand-in, where anyone can still build a plain object by hand. That is the price of a language without module-level privacy, and one reason Racket's boundary contracts are handy.

Choosing between structs, lists and hashes

  • Struct for a fixed set of named fields, with a clear type and predicate.
  • Hash (hash, hasheq) for dynamic keys or data whose shape comes from outside (JSON).
  • List for sequences of similar items, not for records.
  • Vectors when you need fast random access by index.

match (see the interpreter project) can destructure structs in one step, which makes struct-based code concise.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (struct point (x y)) define?

    You get point, point?, point-x and point-y.
  2. 2. What does #:transparent change?

    Transparent structs expose their contents to printing and structural equality.
  3. 3. How do you make a modified copy of an immutable struct?

    struct-copy builds a new struct with some fields replaced; the original is untouched.
  4. 4. How can a module guarantee that no invalid struct exists anywhere?

    If outside code can only build values through the validating function, the invariant holds for every instance.

Summary

  • struct defines a named record with constructor, predicate and accessors; structs are immutable by default.
  • #:transparent enables printing and structural equal?; struct-copy makes modified copies.
  • contract-out can guard struct fields; a hidden constructor plus a smart constructor enforces invariants.
  • Subtypes, guards and properties extend structs when you need them.
  • Use structs for records, hashes for open-ended keys, lists for sequences.

Next: Testing with rackunit