簡體   English   中英

在球拍中使用吸氣劑和吸氣劑實現封閉

[英]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-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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM