Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Lists and Recursion

Vectors and Structs

Use vectors for fast indexed access and structs to define your own record types in Racket. Covers vector-ref, vector-set!, struct fields, transparency and pattern matching.

Lists are wonderful for sequential processing, but two jobs need something else. When you want fast access by position, such as the 500th element, you reach for a vector. When you want to group a few named fields into one value, such as a point with x and y, you define a struct. Both are everyday tools in Racket programs.

The Run examples use the stand-in's vectors and structs. Racket-only features (match, #:mutable, for/vector) are shown read-only.

Vectors

A vector is a fixed-length array. Literal vectors are written with a leading #:

RACKET
#(1 2 3)                       ; a literal vector
(vector 1 2 3)                 ; same, built by a call
(make-vector 4 0)              ; '#(0 0 0 0), four slots filled with 0
(vector-ref v 1)               ; element at index 1, counting from 0
(vector-set! v 1 99)           ; replace element 1
(vector-length v)              ; 3
(vector->list v)               ; '(1 2 3)
(list->vector '(1 2 3))        ; '#(1 2 3)

Access by index takes the same short time wherever the slot is, unlike list-ref. Vectors are mutable when created with make-vector or vector, so vector-set! changes the original, and asking for an index out of range is an error.

Working with vectors

The last line is an error on purpose: index 5 does not exist in a three-element vector. Real Racket reports vector-ref: index is out of range with the index and valid range.

Looping over a vector

Because vectors are indexed, loops over them use a counter. A named let is the idiom:

RACKET
(define (vector-sum v)
  (let loop ([i 0] [total 0])
    (if (= i (vector-length v))
        total
        (loop (+ i 1) (+ total (vector-ref v i))))))

Racket's for forms make this shorter: (for/sum ([x (in-vector v)]) x). The shape of the computation is the same: a counter that advances until the end.

Sum and fill a vector

When to use a list or a vector

List Vector
Access by index Slow (walks the chain) Fast
Add to front Instant (cons) Copy everything
Length known and fixed Not needed Yes
Recursive style Natural Awkward
Mutation Immutable by default vector-set!

A common approach is to process with lists, and convert to a vector only when you need many random accesses.

Structs

A struct defines a new type with named fields. One line gives you a constructor, a predicate and an accessor for each field:

RACKET
(struct point (x y) #:transparent)

(define p (point 3 4))
(point-x p)       ; 3
(point-y p)       ; 4
(point? p)        ; #t
(point? 5)        ; #f
p                 ; (point 3 4)
  • point is the constructor.
  • point-x and point-y are the accessors (named struct-field).
  • point? is the predicate.
  • #:transparent makes the struct print its contents and lets equal? compare fields. Without it, the struct prints as #<point> and two different instances are never equal?.
Defining a struct

The final line shows the contract violation you get from calling an accessor on the wrong kind of value.

Updating structs the functional way

Struct instances are immutable by default. To "change" a field, build a new struct. Real Racket provides struct-copy:

RACKET
(define p2 (struct-copy point p [x 10]))   ; (point 10 4)

You can also write a small helper function that returns a new instance:

RACKET
(define (move-right pt dx)
  (point (+ (point-x pt) dx) (point-y pt)))

If you really need mutation, define the struct with #:mutable to get set-point-x! and friends, but prefer immutable data until you must.

Structs for variants

Structs shine for data that comes in several shapes. Define one struct per shape and a predicate-based cond tells them apart:

Shapes with structs

(We used 3 for pi so the numbers stay exact; real code would use pi.) In real Racket you would write this with match, which destructures a struct in one step:

RACKET
(define (area shape)
  (match shape
    [(circle r) (* pi r r)]
    [(rect w h) (* w h)]))

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (vector-ref (vector 10 20 30) 1) return?

    Indexes start at 0, so index 1 is the second element.
  2. 2. What does #:transparent do in a struct definition?

    A transparent struct exposes its structure, so it prints as (point 3 4) and equal? compares field by field.
  3. 3. Which names does (struct point (x y)) define?

    You get the constructor, the predicate and an accessor for each field.
  4. 4. When is a vector better than a list?

    Vectors give constant-time access by position; lists must walk the chain.

Summary

  • Vectors are fixed-size arrays with fast vector-ref and vector-set!; lists suit sequential recursion.
  • struct defines a constructor, predicate and accessors; #:transparent makes it printable and comparable.
  • Structs are immutable by default; use struct-copy or a helper to produce updated copies.
  • Combine structs with cond (or match in real Racket) to handle several shapes.

Next: Lambda and Closures