Struct Embedding in Scheme
Scheme supports the concept of records, which are similar to structs in other languages. We can use these to demonstrate a concept similar to struct embedding.
;; Define a base record
(define-record-type base
(make-base num)
base?
(num base-num))
;; Define a method for base
(define (describe-base b)
(string-append "base with num=" (number->string (base-num b))))
;; Define a container record that includes a base
(define-record-type container
(make-container base str)
container?
(base container-base)
(str container-str))
;; Main procedure
(define (main)
;; Create a container instance
(let* ((base-instance (make-base 1))
(co (make-container base-instance "some name")))
;; Access fields
(display (string-append "co={num: "
(number->string (base-num (container-base co)))
", str: "
(container-str co)
"}\n"))
;; Access base field directly
(display (string-append "also num: "
(number->string (base-num (container-base co)))
"\n"))
;; Call the base method
(display (string-append "describe: "
(describe-base (container-base co))
"\n"))
;; Demonstrate interface-like behavior
(define (describe obj)
(if (base? obj)
(describe-base obj)
(describe-base (container-base obj))))
(display (string-append "describer: "
(describe co)
"\n"))))
;; Run the main procedure
(main)In this Scheme example, we’ve created a structure similar to the Go code:
We define a
baserecord type with anumfield and adescribe-basefunction that acts like a method.We then define a
containerrecord type that includes abaseinstance and an additionalstrfield. This mimics the embedding behavior in Go.In the
mainprocedure, we create acontainerinstance and demonstrate how to access fields and call methods.We show how to access the
basefields both through thecontainerand directly.To demonstrate interface-like behavior, we define a
describefunction that works with bothbaseandcontainertypes, similar to how thedescriberinterface works in the Go example.
When run, this program will produce output similar to the Go version:
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1Note that Scheme doesn’t have built-in support for object-oriented programming or interfaces. The example above uses functional programming techniques to achieve similar behavior. The concept of “embedding” is simulated by including one record type within another.