简体   繁体   English

在球拍中使用吸气剂和吸气剂实现封闭

[英]Implementing closure using getters and setters in racket

I had to miss a class and am having a bit of trouble figuring out how to get getters and setter to work in racket. 我不得不错过一堂课,并且在弄清楚如何使吸气剂和吸气剂在球拍中工作时遇到了一些麻烦。 I understand the concept in Java, but do not know how to apply it here. 我了解Java中的概念,但不知道如何在这里应用它。 I can't seem to find anything similar or relevant online. 我似乎在网上找不到任何类似或相关的内容。 If anyone would be kind enough to help get me started on the assignment below, I would really appreciate it: 如果有人愿意帮助我开始以下工作,我将不胜感激:

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

Here's one possible implementation of Employee : 这是Employee的一种可能的实现:

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

I'll let you define the rest of the functions. 我将让您定义其余功能。 They should be straightforward (hint: combine get-val or set-val! with first , second , or third ). 它们应该简单明了(提示:将get-valset-val!firstsecondthird )。

Another possible solution is using a dispatch method. 另一种可能的解决方案是使用调度方法。

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

This another way to represent an object. 这是表示对象的另一种方式。 You can then create an employee and get the name as follows: 然后,您可以创建员工并按以下方式获取名称:

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM