Object-oriented Scheme
Can Scheme be object-oriented? Well, for any n, the answer to the question, "Can Scheme be n?" is usually yes. Here is a simple point class:
(define (make-point x y) (lambda (method) (cond ((eq? method 'get-x) x) ((eq? method 'get-y) y) (else 'invalid-method-error)))) (define (make-point x y) ;; Equivalent (uses case for readability) (lambda (method) (case method ((get-x) x) ((get-y) y) (else 'invalid-method-error)))) ;; Usage (define my-point (make-point 1 2)) => # (my-point 'get-x) => 1 (my-point 'get-y) => 2 Questions
- What does the above code do? What is a point?
- How would you modify the definition so that the method can take arguments?
- Can you figure out how to add set-x! and set-y! methods?
- How would you add inheritance? Can you define a colored-point class that has a color as well as x and y coordinates?
Note: This is not quite a complete object system. To make our lives easier, a real object system would define some new special forms, using define-syntax (beyond the scope of this course). A discussion of Scheme object systems might make a good class paper.