(define myobj (create-obj (list (cons "a" (lambda () 1)) (cons "b" (lambda (x) (+ x 2))))))
(myobj "a" '()) ;; => 1
(myobj "b" '(1)) ;; => 3
(define myobj (override myobj (cons "b" (lambda () 11))))
(myobj "a" '()) ;; => 1
(myobj "b" '()) ;; => 11
我想到了类似的东西:
((equal? (car property) "b")
(object "b" '(1)))
而不是发送'(1)作为参数,也许发送一个覆盖方法的帮助函数......
((equal? (car property) "b")
(object "b" (help-func)))
我迷路了......
答案 0 :(得分:1)
我会这样做:
(define (create-obj mlist)
(lambda (method parms)
(case method
((override) (set! mlist (cons parms mlist)))
(else (let ((func (assoc method mlist)))
(if func
(apply (cdr func) parms)
"Error: no such method"))))))
(define myobj (create-obj (list (cons "a" (lambda () 1)) (cons "b" (lambda (x) (+ x 2))))))
(myobj "a" '()) ;; => 1
(myobj "b" '(1)) ;; => 3
(myobj 'override (cons "b" (lambda () 11)))
(myobj "a" '()) ;; => 1
(myobj "b" '()) ;; => 11
或者,没有set!
但使用第二个绑定:
(define (create-obj mlist)
(lambda (method (parms null))
(case method
((get) mlist)
(else (let ((func (assoc method mlist)))
(if func
(apply (cdr func) parms)
"Error: no such method"))))))
(define (override obj func)
(create-obj (cons func (obj 'get))))
(define myobj (create-obj (list (cons "a" (lambda () 1)) (cons "b" (lambda (x) (+ x 2))))))
(myobj "a" '()) ;; => 1
(myobj "b" '(1)) ;; => 3
(define myobj2 (override myobj (cons "b" (lambda () 11))))
(myobj2 "a" '()) ;; => 1
(myobj2 "b" '()) ;; => 11
编辑您似乎正在使用#lang r5rs
:
#lang r5rs
(define (create-obj mlist)
(lambda (method parms)
(case method
((get) mlist)
(else (let ((func (assoc method mlist)))
(if func
(apply (cdr func) parms)
"Error: no such method"))))))
(define (override obj func)
(create-obj (cons func (obj 'get '()))))
(define myobj (create-obj (list (cons "a" (lambda () 1)) (cons "b" (lambda (x) (+ x 2))))))
(display (myobj "a" '())) (newline) ;; => 1
(display (myobj "b" '(1))) (newline) ;; => 3
(define myobj2 (override myobj (cons "b" (lambda () 11))))
(display (myobj2 "a" '())) (newline) ;; => 1
(display (myobj2 "b" '())) (newline) ;; => 11
(newline)