Scheme 在racket中使用getter和setter实现闭包

Scheme 在racket中使用getter和setter实现闭包,scheme,racket,Scheme,Racket,我不得不缺席一节课,在弄清楚如何让能手和二传手在球拍上工作时遇到了一些麻烦。我理解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)

我不得不缺席一节课,在弄清楚如何让能手和二传手在球拍上工作时遇到了一些麻烦。我理解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)))

我将让您定义其余的函数。它们应该简单明了(提示:将
获取val
设置val!
第一个
第二个
,或
第三个
)结合起来。

以下是
员工
的一个可能实现:

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

我将让您定义其余的函数。它们应该简单明了(提示:将
获取val
设置val!
第一个
第二个
、或
第三个
)相结合。

另一种可能的解决方案是使用分派方法

(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)

另一种可能的解决方案是使用分派方法

(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)

令人惊叹的非常感谢你!在你提供的信息之后,我能够填写剩下的内容。谢谢你让我免于一晚上的头痛!令人惊叹的非常感谢你!在你提供的信息之后,我能够填写剩下的内容。谢谢你让我免于一晚上的头痛!我将把这个例子添加到我的笔记中。非常感谢。我将把这个例子添加到我的笔记中。非常感谢。