[plt-scheme] Idiomatic way of calling an object's accessors given dynamic method name?

From: Daniel Yoo (dyoo at cs.wpi.edu)
Date: Mon Feb 19 17:43:54 EST 2007

Hi everyone,


I cooked up the following:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(module test-evil-dynamic-access mzscheme
   (require (lib "class.ss"))

   (define c1%
     (class object%
       (define/public (some-method)
         (printf "foo!~n"))
       (super-new)))


   (define c2%
     (class object%
       (define/public (some-other-method)
         (printf "bar!~n"))
       (super-new)))


   (define (call-method object method-name)
     (define f (make-generic (object-interface object) method-name))
     (send-generic object f))


   (define (test)
     (call-method (new c1%) 'some-method)
     (call-method (new c2%) 'some-other-method))

   (test))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


I know this is abusing the generic mechanism, that it probably isn't meant 
to do something like this, but I think I'll need something like this for a 
project of mine.  I was just checking to see this is using some taboo 
functionality that is likely to be stripped out, or if there's a better 
way of doing this.



Background: I'm trying to implement most of the functionality of Terrence 
Parr's StringTemplate, and one of the things the StringTemplate language 
allows is attribute access a.k.a:

    "In this template, $ object.accessor $ will be interpolated"

I intend to provide similar functionality using the call-method above; the 
syntax will be a little more PLT-Schemeish, something like:

    "In this template, $ (send object get-accessor) $ will be interpolated"

I'm trying to avoid EVAL at all costs.  *grin* So there's only going to be 
a limited set of "special expression forms" between the '$' delimiters. 
In any case, since the interpretation of this is all handled at runtime, I 
can't know the accessor's name in advance, so I need some kind of 
mechanism for calling accessors dynamically.


Best of wishes!


Posted on the users mailing list.