6.001 Recitation #9 – March
7, 2003
RI: Konrad Tollmar
• Some symbols
• Tagged data
1. Self-refences structures
What is the printed form? Write an expression that generate this list.
(define (make-complex-from-rect rl im)
(list
‘rect rl im))
(define (make-complex-from-polar mg an)
(list
‘polar mg an))
(define (tag obj) (car obj))
(define (contents obj) (cdr obj))
(define (real sz)
(cond ((eq?
(tag z) ‘rect) (car (contents z)))
((eq?
(tag z) ‘polar) (* (car (contents z))
;mag
(cos (cadr (contents z))))) ;angle
(else
(error “unknown form of object”))))
;;
some more abstractions
(define
(attach-tag type-tag contents) .. )
(define (type-tag datum) .. )
(define
(contents datum) .. )
(define
(rectangular? z) .. )
(define
(polar? z) .. )
(define
(real-part-rectangular z) .. )
(define
(imag-part-rectangular z) .. )
(define
(make-complex-from-rect rl im ) .. )
(define
(make-complex-from-polar mg an) .. )
(define (real-part z) .. )
A common problem with international software is that different regions have different standard for specify and format daily things like dates etc. For example Swedish dates are formatted as: (year / months / day) compared to American dates (month / day / year). Lets use tagged data to identify Swedish and American date values. First define a procedure that attach a tag and two access procedures that return the tag and the contents.
(define
(attach-tag type-tag contents) .. )
(define (type-tag datum) .. )
(define
(contents datum) .. )
So we can creates datum like:
(define birthday (make-swedish-datum 1969 3 8))
(define today (make-american-datum 3 7 2003))
(define (make-swedish-datum y m d)
(make-from-swedish-datum y m d))
(define (make-from-swedish-datum y m d)
(attach-tag
'swedish (list y m d)))
Next, lets build a procedure day (and month) that can read days and months independent of formats:
(day today) à 7
(month today) à 3
(day
birthday) à 8
(month birthday) à 3
(define (install-rectangular-package)
;; internal
procedures
(define
(real-part z) (car z))
(define
(imag-part z) (cdr z))
...
;;
interface to the rest of the system
(define
(tag x) (attach-tag 'rectangular x))
(put
'real-part '(rectangular) real-part)
(put
'imag-part '(rectangular) imag-part)
...
'done)
;; Generic apply
(define (apply-generic op . args)
(let ((type-tags (map type-tag args)))
(let ((proc (get op
type-tags)))
(if
proc
(apply proc (map contents args))
(error
"No method for these types -- APPLY-GENERIC"
(list op type-tags))))))
;; Generic selectors
(define (real-part z) (apply-generic 'real-part z))
(define (imag-part z) (apply-generic 'imag-part z))