As exercise, I'm trying to implement a small object oriented program, with 2 classes:
point1d: 1 attribute (x), getter and setter
point2d: inherits from point1d, add a new attribute (y) and its getter and setter
I have implemented each class as a closure. This is the code for the first one:
(define (point1d xx)
(let ((x xx))
(define (get-x)
x)
(define (set-x xx)
(set! x xx))
(lambda (f . args)
(apply
(case f
((get-x) get-x)
((set-x) set-x))
args))))
and for the second:
(define (point2d xx yy)
(let ((p1d (point1d xx))
(y yy))
(define (get-y)
y)
(define (set-y yy)
(set! y yy))
(lambda (f . args)
(case f
((get-y) (get-y))
((set-y) (apply set-y args))
(else (p1d f args))))))
I have some problem with the second definition; in the last line i try invoke parents method, but since args
is a list it doesn't work.
What can I do?
In the point2d
lambda, you're trying to call point1d
's functions with
(p1d f (list arg1 arg2 ... argN))
while point1d
expects the arguments to be:
(p1d f arg1 arg2 ... argN)
To solve this, cons
f onto args
, then apply
that to p1d
, like I have done in this fixed definition of p1d
(define (point2d xx yy)
(let ((p1d (point1d xx))
(y yy))
(define (get-y)
y)
(define (set-y yy)
(set! y yy))
(lambda (f . args)
(case f
((get-y) (get-y))
((set-y) (apply set-y args))
(else (apply p1d (cons f args)))))))