Scheme Programming/Record Types

From Wikibooks, open books for an open world
Jump to navigation Jump to search

One of the additions that R7RS provided over R5RS is the ability to define "record types", which are new data types. Record types are disjoint types just like numbers, strings, and pairs. The R7RS syntax is based on SRFI 9, where record types are just a collection of named data fields. If you are familiar with C structs, these are a similar concept. It is possible in Scheme to define objects including methods, as seen in Object Orientation.

In the define-record-type syntax, there are four parts: the name of the type, the constructor, the predicate, and a series of getters and setters.

;; A record type called <animal>
(define-record-type <animal>
  ;; Constructor
  (animal name age species owner-name)
  ;; Predicate
  ;; Getters and setters (omit the setter for immutable fields)
  (name animal-name set-animal-name!)
  (age animal-age set-animal-age!)
  (species animal-species)
  (owner-name animal-owner set-animal-owner!))