在球拍中使用 getter 和 setter 实现闭包

Implementing closure using getters and setters in racket

我不得不错过 class 并且在弄清楚如何让吸气剂和 setter 在球拍中工作时遇到了一些麻烦。我理解 Java 中的概念,但不知道如何在此处应用它。我似乎无法在网上找到任何类似或相关的内容。如果有人愿意帮助我开始下面的作业,我将不胜感激:

(define (box x)
;; when the second item to cons is not
;; a list, we have a pair.
(cons
  (λ() x)
  (λ(y) (set! x y))))

(define (get-val bx)
 ((car bx)))
(define (set-val! bx new-val)
 ((cdr bx) new-val))


;; An employee object is represented as a list of
;; 3 setter-getter pairs
(define (Employee name position salary)
 (error "TBD"))
)


(define (get-name emp)
   (error "TBD")
 )
(define (set-name emp new-name)
  (error "TBD"))

(define (get-position emp)
  (error "TBD"))

(define (set-position emp new-pos)
  (error "TBD"))

(define (get-salary emp)
  (error "TBD"))
(define (set-salary emp new-pos)
  (error "TBD"))

(define prof (Employee "Austin" "Professor" 99999999999999999))

(get-name prof)
(get-position prof)
(get-salary prof)

(set-name prof "Tom the Mighty")
(set-position prof "Master of Time and Space")
(set-salary prof 12345678)

(get-name prof)
(get-position prof)
(get-salary prof)

这是 Employee 的一种可能实现:

(define (Employee name position salary)
  (list (box name) (box position) (box salary)))

我会让你定义其​​余的函数。它们应该简单明了(提示:将 get-valset-val!firstsecondthird 结合使用。

另一种可能的解决方案是使用调度方法。

(define (Employee name position salary)
  (define (get-employee-name)
    name)

;; Your code goes here

  (define (employee-dispatch msg)
    (cond ((eq? msg 'name) (get-employee-name))
          ;; other messages)))

这是表示对象的另一种方式。然后就可以创建员工,取名字如下:

(define mp (Employee))
;; Get the name:
(mp 'name)
;; Set the name (not implemented above):
((mp 'set-name!) new-name)