[plt-scheme] "appending" to classes rather than extending
Matthias Felleisen <matthias at ccs.neu.edu> writes:
> Let's do it with modules:
>
> (module foo mzscheme
> (require scheme/class)
> (provide foo%)
>
> (define foo%
> (class object% (init-field count)
> (super-new)
> (define/public (bar)
> (if (<= count 0)
> (printf "done\n")
> (begin
> (printf "bar\n")
> (set! count (- count 1))
> (send this baz)))))))
>
> (module foo-extended scheme
> (require scheme/class
> 'foo)
> (provide (rename-out (foo-extended% foo%)))
>
> (define foo-extended%
> (class foo% (inherit-field count)
> (super-new)
> (define/public (baz)
> (if (<= count 0)
> (printf "done\n")
> (begin
> (printf "baz\n")
> (set! count (- count 1))
> (send this bar)))))))
>
> (require 'foo-extended)
> (send (new foo% [count 4]) bar)
>
> This uses inheritance to simulate appending. Do you like this better?
> -- Matthias
In Ruby, when you extend types, it affects existing objects of that
type too. Below, my_object is bound to an object created when X is an
"empty" class, and then I add a bar method, and it's immediately
available.
class X
end
my_object = X.new
class X
def bar
puts "BAR"
end
end
my_object.bar # This works
Out of curiousity, is that (or something like that) possible with the
mzScheme object model?
(I don't understand the details of modules or classes in scheme well
enough to really answer this myself.)
--
Chris