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:

  1. We define a base record type with a num field and a describe-base function that acts like a method.

  2. We then define a container record type that includes a base instance and an additional str field. This mimics the embedding behavior in Go.

  3. In the main procedure, we create a container instance and demonstrate how to access fields and call methods.

  4. We show how to access the base fields both through the container and directly.

  5. To demonstrate interface-like behavior, we define a describe function that works with both base and container types, similar to how the describer interface 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=1

Note 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.