shriram / plai-public

Repository for (for now) filing bug reports about PLAI.
6 stars 0 forks source link

Provide example of access to private variables in other instances #26

Open bremner opened 10 months ago

bremner commented 10 months ago

Contact Details

bremner@unb.ca

Which part are you commenting on?

p. 89 v3.2.2

What's your suggestion?

Thinking about the "Private Member" discussion (i.e. #24 and #25), I think it would be nice to give an example of accessing the private members of another object. The best I could come up with uses gensym; I would be happy to see it improved. As it stands it probably would go most naturally after the introduction of static/class variables.

#lang racket

(require [only-in plait test test/exn error print-only-errors])

(define (msg obj selector . args)
  (apply (obj selector) args))

(define mk-num
  (let ([secret (gensym)])
    (lambda (init)
      (let ([amount init])
        (lambda (m)
          (cond
            [(equal? m secret) (lambda () amount)]
            [(equal? m 'add)
             (lambda (other)
               (mk-num (+ amount (msg other secret))))]
            [(equal? m 'odd?) (lambda () (odd? amount))]))))))

(define o2 (mk-num 2))
(define o3 (mk-num 3))
(define o4 (msg o2 'add o2))
(define o5 (msg o2 'add o3))
(test (msg o2 'odd?) #f)
(test (msg o3 'odd?) #t)
(test (msg o4 'odd?) #f)
(test (msg o5 'odd?) #t)