[plt-scheme] How to get a function from the symbol representing it?

From: Carl Eastlund (cce at ccs.neu.edu)
Date: Wed Apr 9 16:30:23 EDT 2008

On Wed, Apr 9, 2008 at 4:09 PM, Grant Rettke <grettke at acm.org> wrote:
> I was reading the comp.lang.lisp post [Two Questions about Functions]
>  where the poster asks how to evaluate a function, given only a string
>  representing the function name.
>  Is this something that happens very often in Scheme programs?
>  1. Take the string of the function name "max"
>  2. Get the function max for that function name
>  3. Apply that function to some arguments
>  I'm under the impression that the only way you can take a string and
>  get the function represented by the symbol that the string represents
>  is to use eval, quasiquote, and string->symbol
>  (eval `(,(string->symbol "max") 1 2 3 4) (scheme-report-environment 5))
>  Is that true?

You are correct that eval is the only way to evaluate a string (or any
value) as Scheme code.  This is not common in Scheme code, but it is a
common error by beginners to functional languages.  Novices are not
used to higher order programming and passing around functions as
values, but they are used to passing strings around.  So, around goes
the string, and at the application site it has to magically turn into
a function.  Eval to the rescue!

There are other solutions, pretty much any of which are preferable.
One, pass the function around itself.  Lambda is your friend.  Two, if
you do want to be able to report names to the user (say if the
matching function is not found), pass a string or symbol around and
use a hash table to relate names to the actual function you want.
Either way, the mapping between values and functions is represented in
the original program, not in other code to be compiled and evaluated

Eval is a major pitfall; it's a heavy-weight solution with a lot of
subtleties and drawbacks that aren't apparent at first glance.  Avoid
it at all costs unless your actual task is to take Scheme code and
evaluate it.  Then, of course, eval is 95-100% of your program.

Carl Eastlund

Posted on the users mailing list.