Reputation: 518
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. 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)
Upvotes: 1
Views: 645
Reputation: 2922
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)
Upvotes: 2
Reputation: 223043
Here's one possible implementation of 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
).
Upvotes: 2