One problem on one of my practice exams is centered around message passing and data directed program. It asks for a procedure that utilizes the table initializing these install packages:
(define (attach-tag tag data) (cons tag data))
(define (get-tag data) (car data))
(define (get-contents data) (cdr data))
(define (install-metric-package)
; internal procedures
(define (get-kilometers d) d)
(define (get-miles d) (/ d 1.6))
(define (make-from-kilometers d) d)
(define (make-from-miles d) (* d 1.6))
; install metric packages
(2d-put! 'get-kilometers 'metric get-kilometers)
(2d-put! 'get-miles 'metric get-miles)
(2d-put! 'make-from-kilometers 'metric
(lambda(d) (attach-tag 'metric (make-from-kilometers d))))
(2d-put! 'make-from-miles 'metric
(lambda(d) (attach-tag 'metric (make-from-miles d))))
'done)
(define (install-english-package)
; internal procedures
(define (get-kilometers d) (* d 1.6))
(define (get-miles d) d)
(define (make-from-kilometers d) (/ d 1.6))
(define (make-from-miles d) d)
; install english packages
(2d-put! 'get-kilometers 'english get-kilometers)
(2d-put! 'get-miles 'english get-miles)
(2d-put! 'make-from-kilometers 'english
(lambda(d) (attach-tag 'english (make-from-kilometers d))))
(2d-put! 'make-from-miles 'english
(lambda(d) (attach-tag 'english (make-from-miles d))))
'done)
and allows the generic operators to work. Normally, I would have some code to show effort on my part, but for about a day, I’ve been completely stumped on how to even BEGIN with this one. All I’m given to start with is this:
(define (generic-op operator object)
I do remember having a lab on this, but it was basically taking an already-existing generic procedure and creating simple procedures to get values already contained within it. If anyone can shed some light on how to approach this, I would appreciate it greatly. Again, I’m sorry that I have nothing to show on my part, but I honestly do not know what to do here.
The
2d-put!procedure is simply adding entries to the table. After you run theinstall-*-packagecode you end up with something like this (where[proc]is one of the procedures defined in your given code):Then you’re going to use
2d-getin the body ofgeneric-opso that whenever you call the procedure on a piece of tagged data your program will know which version (metric/english) of the procedure it should use.In this form the
[first-tag]will just be the symbol used to designate the operator, e.g.'get-miles, the[second-tag]will be the symbol that was attached to the data which you can access with the given procedureget-tag, and[data]is the number that you actually want to do the operation on which you can access with the given procedureget-contents. Assemble all that into a final answer for something like this: