Structs, Records and Methods
Sigil gives you two ways to define your own data types and one way to write procedures that behave differently for each type:
define-structfrom(sigil struct)makes a type with a fixed set of fields. Instances are compact, field access is fast, and the instance is opaque: you reach its fields through the accessors the macro generates.define-recordfrom(sigil record)makes a type whose instances are immutable dicts. Every dict operation works on them, and they can carry extra keys beyond their declared fields.(sigil method)provides multimethods: one procedure name with a separate implementation per type, chosen at call time. Methods can dispatch on struct types, record types and built-in types, and any module can add a method.
This guide covers each of them, how they print, and how to choose between them.
Structs
Defining a Struct
List each field in its own parentheses:
(import (sigil struct))
(define-struct point
(x)
(y))This defines:
point, a constructor that takes one keyword argument per field;point?, a predicate;point-xandpoint-y, accessors.
(define p (point x: 3 y: 4))
(point-x p) ; => 3
(point? p) ; => #t
(point? 42) ; => #fEach field needs its own parentheses. (define-struct point (x y)) declares one field, x, and treats y as that field's type predicate, so (point x: 1 y: 2) then fails with point: unknown field y.
Defaults and Missing Fields
Give a field a default with default::
(define-struct account
(owner)
(balance default: 0)
(tags default: '()))
(account owner: "ada")
; => #<account owner: "ada" balance: 0 tags: ()>A field with no default that the caller leaves out is not an error. It holds an undefined value:
(account)
; => #<account owner: #<undefined> balance: 0 tags: ()>If a field must always be supplied, check it in a procedure that builds the struct. A keyword that names no field is an error: (account owner: "x" bogus: 1) raises account: unknown field bogus.
Mutable Fields
Fields are immutable unless you mark them mutable: #t. A mutable field gets a setter named set-TYPE-FIELD!:
(define-struct counter
(value default: 0 mutable: #t))
(define c (counter))
(set-counter-value! c 10)
(counter-value c) ; => 10Immutable fields have no setter at all, so a call to set-counter-label! for an immutable label field is an unbound variable error.
Copying with Changes
Pass an existing instance as the first argument to the constructor to copy it with some fields replaced:
(define a (account owner: "ada" balance: 50))
(define b (account a owner: "bob"))
b ; => #<account owner: "bob" balance: 50 tags: ()>
(account-owner a) ; => "ada"The copy is a separate instance, so setting a mutable field on the original later doesn't change the copy. The copy is shallow: a list or vector held in a field is shared between the two.
struct-update copies a struct and transforms fields with procedures, which saves reading the old value yourself:
(struct-update b balance: (lambda (n) (+ n 1)))
; => #<account owner: "bob" balance: 51 tags: ()>It works on any struct type, and raises on a field the type doesn't have.
Equality
equal? compares struct instances by identity. Two structs with the same fields are not equal? unless they are the same instance. Use struct-equal? to compare fields:
(equal? (account owner: "x") (account owner: "x")) ; => #f
(struct-equal? (account owner: "x") (account owner: "x")) ; => #tstruct-equal? compares fields with equal? and recurses into fields that are themselves structs. A struct inside a list or vector field still compares by identity, because equal? does. Instances of different types are never struct-equal?.
Embedding Another Struct
include: gives a struct all the fields of another struct, followed by its own:
(define-struct person
(name)
(age default: 0))
(define-struct employee include: person
(dept default: "eng"))
(define e (employee name: "Ada" age: 36))
e ; => #<employee name: "Ada" age: 36 dept: "eng">
(employee-name e) ; => "Ada"
(person-name e) ; => "Ada"
(person? e) ; => #t
(employee->person e)
; => #<person name: "Ada" age: 36>An employee satisfies person?, and both the parent's accessors and the child's accessors for inherited fields work on it. employee->person builds a new person from the inherited fields. Multimethods also treat the parent's method as the child's default (see Inheritance and Fallback).
Field Predicates and Specs
A predicate after the field name documents the field's type:
(define-struct server
(host string?)
(port integer? default: 8080))The macro turns these into procedure specs on the constructor and accessors, so (procedure-spec server-port) returns (server? -> integer?). Neither the constructor nor a setter checks the predicate, even with spec checks turned on. The procedure specs guide explains what is checked and when.
The struct's own predicate, such as server?, is a good predicate for specs of procedures that take the struct.
Inspecting Struct Types
(sigil struct) also exports procedures for working with struct types at runtime:
| Procedure | Returns |
|---|---|
(struct? x) | #t for any struct instance |
(struct-type-of s) | the instance's type descriptor |
(struct-type-name t) | the type's name, a symbol |
(struct-type-field-names t) | the type's own fields, not inherited ones |
(struct-type-parent t) | the include: parent's descriptor, or #f |
(struct-type-name (struct-type-of e)) ; => employee
(struct-type-parent (struct-type-of e)) ; => #<struct-type person>Printing Structs
display and write print a struct as its type name and fields:
(define-struct label (text) (at))
(define l (label text: "origin" at: (point x: 0 y: 0)))
(display l) ; prints #<label text: origin at: #<point x: 0 y: 0>>
(write l) ; prints #<label text: "origin" at: #<point x: 0 y: 0>>As with other values, write quotes strings and display doesn't, and nested structs print the same way. write also marks a value that appears more than once in the same output with a label, so a list holding the same struct twice prints as:
(#0=#<point x: 0 y: 0> #0#)
format, println's format directives and str don't use the struct printer. They print a struct as #<object>:
(format "~a" (point x: 1 y: 2)) ; => "#<object>"To get the printed form as a string, write to a string port:
(call-with-output-string
(lambda (port) (write (point x: 1 y: 2) port)))
; => "#<point x: 1 y: 2>"Records
Defining a Record
define-record uses the same field syntax as define-struct, including default: and a type predicate:
(import (sigil record))
(define-record buffer
(name string?)
(size default: 0))
(define-record file-buffer include: buffer
(path))
(define b (file-buffer name: "main.sgl" path: "/src/main.sgl"))It defines a keyword constructor, a predicate and accessors, as define-struct does. The difference is the instance: a record is an immutable dict tagged with its type.
(file-buffer? b) ; => #t
(buffer? b) ; => #t
(dict? b) ; => #t
(buffer-name b) ; => "main.sgl"
(dict-ref b path:) ; => "/src/main.sgl"A record type with include: doesn't get its own accessors for inherited fields. Use the parent's accessor, buffer-name, or dict-ref.
Working with Records as Dicts
Because a record is a dict, it behaves like one in the places a struct would not:
- Copying: passing a record as the constructor's first argument returns an updated copy with the same type, like structs.
dict-setalso keeps the type:(file-buffer? (dict-set b note: "x"))is#t. - Extra keys: the constructor accepts keys that aren't declared fields and stores them.
(buffer name: "a" bogus: 1)succeeds. - Missing fields: a field with no default that the caller leaves out is absent from the dict, and its accessor returns
#f. - Equality:
equal?compares records like dicts, by content. - Pattern matching: match a record with a dict pattern such as
(#{ name: n } n). The struct pattern(: buffer name:)doesn't match records.
The type tag is an ordinary entry under the key sigil/record-type:, so dict-keys includes it. Treat that key as reserved.
Remove the tag before you hand a record to a serializer. The tag's value is the type descriptor, and json-encode on a record fails with a stack overflow. Encode the plain dict instead:
(import (sigil json))
(json-encode (dict-remove (buffer name: "a") sigil/record-type:))
; => "{\"size\":0,\"name\":\"a\"}"Printing Records
display and write print a record like a struct, with its type name and its entries:
(write (buffer name: "a"))
; prints #<buffer size: 0 name: "a">
(write b)
; prints #<file-buffer size: 0 name: "main.sgl" path: "/src/main.sgl">The entries print in the dict's key order, not the declaration order: fields filled from defaults come first, then the keys in the order the constructor received them. Extra keys print too, and an absent field doesn't. As with structs, format and str print a record as #<object>.
R7RS define-record-type
The standard R7RS form define-record-type isn't part of the core library. It comes from the sigil-r7rs package, through (scheme base) or (srfi srfi-9):
(import (srfi srfi-9))
(define-record-type <point>
(make-point x y)
point?
(x point-x)
(y point-y set-point-y!))These records are neither structs nor define-record records. An instance is a vector whose first element is the type name symbol:
(define p (make-point 1 2))
(display p) ; prints #(<point> 1 2)
(vector? p) ; => #t
(struct? p) ; => #fSo equal? compares them by content, multimethods dispatch on them as 'vector, and any vector that starts with the symbol <point> satisfies point?. Use define-record-type for code that must also run on other Scheme implementations, and define-struct for Sigil code.
Choosing Between Them
define-struct | define-record | define-record-type | |
|---|---|---|---|
| Representation | fixed slots | immutable dict | tagged vector |
| Extra keys | no | yes | no |
| Mutable fields | with mutable: #t | no | with a setter name |
equal? | identity | content | content |
| Dict operations | no | yes | no |
| Multimethod dispatch | its type | its type | 'vector |
| Where it comes from | (sigil struct) | (sigil record) | sigil-r7rs package |
Use a struct for a value with a known, fixed shape, such as a point, a token or a game entity, especially where access speed matters. Use a record when the value is open data that moves through your program: it may gain extra keys, or you want to reach it with generic dict procedures. Remove the type tag before encoding a record as JSON.
Pattern Matching on Structs
match from (sigil match) destructures a struct with the (: type field: ...) pattern:
(import (sigil match))
(match (point x: 1 y: 2)
((: point x: y:) (+ x y))) ; => 3The Functional Programming Style guide covers the pattern in detail, including field tests and renaming. For records, use a dict pattern instead.
Methods
Multimethods
A multimethod is a procedure with a separate implementation, a method, for each type of its first argument. Define the multimethod with define-multi, then add methods with define-method:
(import (sigil method) (sigil string))
(define-multi show)
(define-method show (s 'string)
(string-append "\"" s "\""))
(define-method show (n 'number)
(number->string n))
(define-method show (items 'list)
(string-append "[" (string-join (map show items) ", ") "]"))
(define-method show (x default:)
(string-append "<" (symbol->string (type-name (value-type x))) ">"))
(show "hi") ; => "\"hi\""
(show '(1 "two")) ; => "[1, \"two\"]"
(show 'sym) ; => "<symbol>"In (define-method show (s 'string) ...), s is the parameter name for the first argument and 'string is the type the method handles. Further parameters follow, as in (define-method area (s 'dict scale) ...), and every method receives all the arguments of the call.
Dispatch Types
The type position of define-method accepts:
- a struct or record constructor, such as
pointorbuffer, which works across modules; - a struct or record type descriptor;
- a quoted built-in type symbol:
'string,'symbol,'keyword,'number,'boolean,'char,'list,'null,'vector,'bytevector,'dictor'procedure; 'other, for any value outside those types, such as a port;default:, the method used when nothing else matches.
value-type returns the type a value dispatches on, and type-name turns it into a symbol for messages. Two cases need care:
'listcovers pairs only. The empty list is'null, so a method for'listdoesn't receive'().- A record dispatches on its record type, never on
'dict. If neither the record's type nor its parents have a method, the call uses thedefault:method if there is one, and never a'dictmethod.
A call with no matching method and no default: method raises multimethod: no method for TYPE.
Inheritance and Fallback
When a struct or record type has no method of its own, dispatch tries its include: parent, then the parent's parent, and finally the default: method:
(define-struct shape (label default: ""))
(define-struct circle include: shape (radius))
(define-struct square include: shape (side))
(define-method show (c circle)
(string-append "circle r=" (show (circle-radius c))))
(define-method show (s shape)
(string-append "shape " (show (shape-label s))))
(show (circle radius: 2)) ; => "circle r=2"
(show (square label: "box" side: 3)) ; => "shape \"box\""square has no method, so it uses the shape method.
Extending a Multimethod from Another Module
Any module that imports a multimethod can add methods to it. This is how you teach a library's multimethod about your own types without changing the library. A library exports the multimethod:
;;; (app show) - Render values as short text.
(define-library (app show)
(import (sigil method) (sigil string))
(export show)
(begin
(define-multi show)
(define-method show (s 'string)
(string-append "\"" s "\""))
(define-method show (x default:)
(string-append "<" (symbol->string (type-name (value-type x))) ">"))))Your module imports it and adds methods for its own types:
(define-library (app shapes)
(import (sigil struct) (sigil method) (app show))
(export circle circle?)
(begin
(define-struct circle (radius))
(define-method show (c circle)
(string-append "circle r=" (number->string (circle-radius c))))))define-method registers the method when the module that contains it loads. Code that calls show sees the circle method once (app shapes) has been imported anywhere in the program.
Registering a method for a type that already has one replaces it, and the next call uses the new method. This makes it safe to redefine methods at the REPL while you work.
Custom Dispatch
By default a multimethod dispatches on the type of its first argument. Pass dispatch: to compute the dispatch key from the arguments instead:
(define-multi handle-event
dispatch: (lambda (event) (dict-ref event kind:)))
(define-method handle-event (e 'click)
(format "click at ~a,~a" (dict-ref e x:) (dict-ref e y:)))
(define-method handle-event (e 'key)
(format "key ~a" (dict-ref e key:)))
(handle-event #{ kind: 'click x: 3 y: 4 }) ; => "click at 3,4"Keys are compared with eq?, so use symbols, keywords, characters or small integers as keys, not strings or lists. default: stays reserved as the fallback key.
Inspecting Multimethods
multi? tests whether a value is a multimethod, and multi-methods returns the registered dispatch keys and methods as an alist:
(map car (multi-methods show))
; => (#<struct-type shape> #<struct-type circle> default: list number string)A method body can begin with a procedure spec. The spec belongs to that method, not to the multimethod.
Summary
- Use
define-structfor fixed-shape values. Supply every field without a default, compare withstruct-equal?, and copy with the constructor orstruct-update. - Use
define-recordfor open, dict-shaped data. Dict operations,equal?and dict patterns work on it. define-record-typecomes fromsigil-r7rsand makes tagged vectors. Use it for portable code.displayandwriteprint structs and records as#<type field: value ...>.formatandstrprint#<object>, so write to a string port when you need the text.define-multianddefine-methoddispatch on struct, record and built-in types, fall back throughinclude:parents todefault:, and accept methods from any module.