sigildocs

Records

Structured data types with define-struct and define-record-type.

define-struct

Sigil's idiomatic struct syntax with keyword constructors, defaults, and inheritance.

Important: You must import (sigil struct) to use define-struct:

(import (sigil struct))
(define-struct point
  (x default: 0)
  (y default: 0))

(define p1 (point))              ; x=0, y=0
(define p2 (point x: 10))        ; x=10, y=0
(define p3 (point x: 10 y: 20))  ; x=10, y=20

(point-x p3)  ; => 10
(point? p1)   ; => #t

Field Options

(define-struct config
  (host default: "localhost")    ; Default value
  (port default: 8080)
  (debug default: #f mutable: #t)) ; Mutable field

(define c (config))
(set-config-debug! c #t)

Inheritance

Use include: (outside field list) to embed another struct's fields.

(define-struct point2d
  (x default: 0)
  (y default: 0))

(define-struct point3d
  include: point2d
  (z default: 0))

(define p (point3d x: 1 y: 2 z: 3))
(point3d-x p)  ; => 1  (inherited accessor)
(point3d-z p)  ; => 3

Generated Names

For a struct named foo with field bar:

  • Constructor: foo
  • Predicate: foo?
  • Accessor: foo-bar
  • Mutator: set-foo-bar! (if mutable)

define-record-type

R7RS/SRFI-9 style record definitions for Scheme compatibility. Use define-struct for new code.

(define-record-type <point>
  (make-point x y)
  point?
  (x point-x)
  (y point-y))

(define p (make-point 10 20))
(point? p)      ; => #t
(point-x p)     ; => 10
(point-y p)     ; => 20

Syntax

(define-record-type <type-name>
  (constructor-name field ...)
  predicate-name
  (field-name accessor-name)
  (field-name accessor-name modifier-name)
  ...)

Mutable Fields

Add a modifier name to make a field mutable.

(define-record-type <counter>
  (make-counter value)
  counter?
  (value counter-value set-counter-value!))

(define c (make-counter 0))
(set-counter-value! c 10)
(counter-value c)  ; => 10

Partial Constructors

The constructor can take a subset of fields.

(define-record-type <person>
  (make-person name)    ; Only name in constructor
  person?
  (name person-name)
  (age person-age set-person-age!))

(define p (make-person "Alice"))
(set-person-age! p 30)

Choosing Between Them

Use define-struct when:

  • Writing new Sigil code
  • You want keyword constructors
  • You need default values
  • You want inheritance

Use define-record-type when:

  • Porting R7RS or SRFI-9 code
  • You need explicit control over all names
  • Interoperating with other Scheme code

Printing

Records print with their type and field values:

(define-struct person (name) (age))
(person name: "Alice" age: 30)
; => #<person name: "Alice" age: 30>