[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
uses for eval
Alistair Bayley wrote:
> Sorry to drag the conversation back a couple of days, but can
> someone please tell me what you would use an "eval" function for?
> What problem might you be trying to solve that would be cumbersome
> in a language without an "eval"?
One thing I use eval for is in some server programs, to evaluate program
code fragments provided by clients. This provides a very high-level
client/server communication mechanism. Lack of eval, or the ability to
compile and dynamically load code, would mean that you'd have to implement a
custom interpreter for the received code, or more likely, you'd implement a
parser for a custom protocol which would be much less flexible.
Another use for eval is where the user has some significant control over the
program to be evaluated. For example, a graphing program that allows the
user to specify transformations to be applied to the data before plotting.
In cases like that, it can be useful to allow the user to enter ad-hoc
expressions, and having eval can make it much easier to deal with these
expressions. Again, the alternative is typically to write a custom
expression interpreter (been there, done that, prefer eval).
Then there are systems that are configured via configuration data which may
contain code fragments. Again, eval is useful here. One alternative
approach in this case is to transform the configuration data into source
code which is included in the final program, i.e. turn the dynamic
configuration file into part of a static program. Using eval can eliminate
this step and simplify configuration.
There are potential tradeoffs in all of these cases. One issue which can
arise is security: allowing a program to execute arbitrary code fragments
from external sources can be a bad thing. However, it's usually easier to
deal with this than to write alternatives to eval - for example, you can
scan the code to be executed to ensure that it only calls approved
functions. Along these lines, there's a very powerful capability in PLT
Scheme to very easily define restricted sublanguages (or other languages),
which is ideal for this sort of application.
Performance can be another tradeoff. If a program uses eval to the point
where performance becomes an issue, alternative approaches may be needed.
In the sort of applications I've described, though, this isn't usually a
concern.
In the evolution of a system over time, uses of eval are sometimes replaced
by less dynamic alternatives, usually because of some of the tradeoffs I've
mentioned. But this is almost always less flexible and more cumbersome. At
the very least, eval can be very useful during a prototyping phase, and in
systems that are undergoing significant change or growth.
Anton