A few examples of Dynamic Language eval Techniques

Source: Internet
Author: User

In the previous post, "What do I recommend Python [2]?

The eval method commonly used in dynamic languages is mentioned. At that time, in order to impress everyone, I gave an example of digital operations (for details, see "original article ".
) To describe the benefits of eval.

Later, a "talented" Student mentioned in his reply that the following pre-compilation statements can be used to solve the problem:
# Define Foo (OP, P1, P2) (P1 op P2)

I disagree with this. Whether using the C/C ++ preprocessing syntax to define macro functions, there are some inherent defects. Simply put, this method can meet the needs of this example.Scalability

This is a problem.

I guess: first, the example of last week was too simple to show the eval skills fully. Second, some people did not experience the strong pleasure of eval. Therefore, I decided to take the eval topic into consideration and give a few more examples. Statement in advance: eval skills fooled in this article, most dynamic languages

. Considering that I am familiar with python, the examples in this article use The py code to show.

Example 1

First, expand the previous example to extend some operation of two numbers to some operation of multiple numbers. That is to say, given a certain type of operation (for example, "*" indicates multiplication, "+" indicates addition) and a number of numbers, the operation result must be returned.

Example:

Given: "+" and 4, 5, 6, return 15.

Given: "*" and 2, 3, 4, 5, 120 is returned.

For non-dynamic languages such as C/C ++/Java, a function with two parameters must be defined. One parameter represents the operation type, and the other parameter represents the array. As for function implementation, it is basically still
Those tricks. You can either use a switch to get the process-oriented path, or abstract an interface class for calculation (pure virtual class ), then different implementations are derived for each operator (such as Addition
Class, multiplication class)-that is, the path to object-oriented. Of course, anyone who wants to show off the C/C ++ macro skills may also be able to use macro functions, but the code is much more complicated than it was previously.

Now let's take a look at how Python's eval function meets this requirement. Compared with the original two lines of code, this time it is a little more complex and changed to five lines. The idea is still the same as the original one. First format the string of an arithmetic expression and then discard all other work to eval.

Def Foo (soperator, lstvalues ):
Sexpr = "";

For N in lstvalues [1:]: # skip the first element

Sexpr + = (soperator + STR (n ));
Return eval (STR (lstvalues [0]) + sexpr); # Add the first element and evaluate it

When calling, you only need to write print Foo ("+", [2, 3, 4, 5]) to print 14.

Example 2

In Example 2, we continue to complicate the requirements. Assume that you want to implement something similar to a calculator so that users canRuntime

Input
Enter a four-character arithmetic expression and calculate the result. Support for common four-Rule operators and support for priority (parentheses) between operators ). In this case, if you attempt to use a static language
Yes (not relying on third-party libraries), you need to pay for the boss's strength. In python, the code is simpler than Example 1 (an eval Statement ).

Example 3

Some of you may not be convinced that you are engaged in numerical operations. Are there any new tricks? Of course, the eval method is not limited to numerical operations! The following describes how Eval is applied to new occasions.

For ease of understanding, I will take the mail client as an example (it is estimated that 99.9% of students have used it ). The mail client has a common requirement: You can configure some filtering rules to filter some spam.

Suppose we want to develop a cool client, and its filtering rules should be strong enough: we can determine the conditions based on the different attributes of the email (the required personnel must support the following attributes: title, body, and sender
Number of people, recipients, and attachments ). To reflect the knowledge of the software, the requirement personnel requires that users can set a variety of flexible nested logical combinations. For example, you can configure the following judgment rule:

If (the title includes "dating" and (the sender is from "QQ.com" or the sender is from "kaixin.com") or the number of attachments is greater than 10, it is considered as spam.

Of course, I used the above pseudo code to describe it easily. The real users are all dummies. We must provide a dummies interface for users to configure filtering rules.

 
The interface design is not the focus of this article. Currently, the key question is, if you want to support such complex nested logic expressions, what should the background filter engine do? It is estimated that some students already
As you can see, it is very tricky to use static languages to process them-because the rules are configured randomly by the user at runtime, and the layers of logical nesting are not fixed, email attributes may be extended in the future.

At this time, the eval method can shine again. If you have configured the filter rule, the interface module only needs to generate the source code for the next Python function (to put it bluntly, it is a string ).

Def filter (stitle, scontent, sfrom, sto, nattachnum ):

If (stitle. Find ("friend ")! =-1 and (sfrom. Find ("@ QQ.com ")! =-1 or
Sto. Find ("@ kaixin.com ")! =-1) or nattachenum> 10:

Return true;
Else:

Return false;

The background module can first create a filter function using the aforementioned string through the built-in exec function of Python. After receiving an email, you only need to pass the attributes of the email to the filter function to complete spam determination.

By the way: If you like the OO style, you can refactor the above Code, add a mail class, and use filter as a mail method. If you like the pythonic style, you can also change the above Code to a more concise way.

Summary

Finally, let's make a concluding speech. The secret of this method is that the string passed to eval/exec can be viewedData
Can also be seen as executableCode

. In the eval Technique of Dynamic Language, data and code are perfectly combined. With this combination, you get the ability to generate code at runtime.

 


Copyright Notice

All original articles in this blog are copyrighted by the author. This statement must be reprinted to keep this article complete, and the author's programming will be noted in the form of hyperlinks
And the original address of this article:

Http://program-think.blogspot.com/2009/08/examples-of-eval.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.