Methods in Scheme

Scheme supports procedures defined on custom data types, which we can implement using records.

(define-record-type rect
  (make-rect width height)
  rect?
  (width rect-width)
  (height rect-height))

;; This `area` procedure operates on a `rect` record.
(define (area r)
  (* (rect-width r) (rect-height r)))

;; Here's another procedure that operates on a `rect`.
(define (perim r)
  (+ (* 2 (rect-width r)) (* 2 (rect-height r))))

(define (main)
  (let ((r (make-rect 10 5)))
    ;; Here we call the 2 procedures defined for our record.
    (display "area: ")
    (display (area r))
    (newline)
    (display "perim: ")
    (display (perim r))
    (newline)))

(main)

To run the program, save it in a file (e.g., methods.scm) and use your Scheme interpreter. For example, if you’re using Guile:

$ guile methods.scm
area: 50
perim: 30

In Scheme, we don’t have the concept of methods attached to objects like in object-oriented languages. Instead, we define procedures that operate on our custom data types (records in this case). The area and perim procedures take a rect as an argument and perform calculations based on its properties.

Scheme doesn’t have a built-in distinction between value and reference semantics like some other languages. The behavior depends on how the Scheme implementation handles records. In many implementations, records are handled by reference, so there’s no need for explicit pointer manipulation.

Next, we’ll look at Scheme’s mechanism for creating abstract interfaces: generic procedures and method dispatch.