[英]Implementing closure using getters and setters in 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)
这是Employee
的一种可能的实现:
(define (Employee name position salary)
(list (box name) (box position) (box salary)))
我将让您定义其余功能。 它们应该简单明了(提示:将get-val
或set-val!
与first
, second
或third
)。
另一种可能的解决方案是使用调度方法。
(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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.