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

时间:2015-09-18 03:54:07

标签: 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)
 ((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)

2 个答案:

答案 0 :(得分:2)

以下是Employee

的一种可能实现方式
(define (Employee name position salary)
  (list (box name) (box position) (box salary)))

我会让你定义其​​余的功能。它们应该是直截了当的(提示:将get-valset-val!firstsecondthird合并。

答案 1 :(得分:2)

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

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