[racket] Dynamically calling struct accessors/method names

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Tue Sep 6 14:22:42 EDT 2011

In Racket, accessors are functions and are thus perfectly legitimate arguments: 

(define (foo some-posn some-accessor)
  (some-accessor some-posn))

> (foo my-posn posn-x)
3





On Sep 6, 2011, at 2:17 PM, Todd Bittner wrote:

> Hi, 
> 
> I'm trying to something along the following lines:
> 
> > (define-struct posn (x y))
> > (define my-posn (3 4))
> > (define (foo posn-instance field)
>         (posn-field posn-instance))
> 
> where calling 
> 
> (foo my-posn "x")  
> 
> would dynamically substitute posn-field with posn-x and the function would return 3.
> 
> I don't know what to do with either "x" or posn-field to get this to work.  I *think* I'm looking for something like a string->function function, where I could pass in "x" and posn-field would be replaced by 
> 
> (string->function (string-append "posn-" field)) 
> 
> I just don't know if there's something that currently serves that purpose or, if not, how to go about creating that function.
> 
> Thanks, 
> 
> Todd
> _________________________________________________
>  For list-related administrative tasks:
>  http://lists.racket-lang.org/listinfo/users




Posted on the users mailing list.