What did Meta programming solve the problem primarily?

Source: Internet
Author: User
Tags rebol javascript string concatenation
metaprogramming is the writing of computer programs This write or manipulate other programs (o R themselves) as their data, or that does part of the work at compile time this would otherwise be don E at runtime . In some cases, this allows programmers to minimize the number of lines of code to express a solution (hence reducing devel Opment time), or it gives programs greater flexibility to efficiently handle new situations without recompilation.
Have not contacted Meta programming, feel "manipulate other programs (or themselves) as their data" This is a bit false, can give some exact examples to illustrate its magical place?
Also, why is Lisp and Ruby doing better than Python on meta programming?

Reply content:

If meta-programming is defined as programming to manipulate programs, there seems to be no reason to exclude eval from metaprogramming.
As to whether it should be compiled or run-time, I think it really does not matter.
Meta-programming is obviously more of an abstraction level, which is equivalent to allowing you not only to abstract problems through one level, but also to abstract your problem model through another level. If used well, it seems to provide a tremendous amount of energy. However, it also seems to go beyond the rules of the brain of most people and is less suited to large-scale promotion.
As for Monad, if you focus on it can be redefined, that is, the ability to define the sequence of operations, but also barely can be considered meta-programming bar.
Say a digression:
Someone above mentioned Rebol, said its meta-programming is not good, I feel distinctly different. Since Rebol uses the simplest syntax as its form, this leads to a custom dialect that is so natural and intuitive that its meta-programming is more natural and more beautiful. Ruby Meta-Programming The introduction of this book is actually quite clear.
I am suggesting that you read this book, I believe you can understand, the example is good, this book I have not read. I'm on hand right now.
By the way, Lisp, we all know that "code and data" is actually the same thing. The definition of meta-programming is to write code code, lisp inside the quote can block evaluation, to use when the need for eval on the line. Then manipulating your code while running is another implication for him. You can call it called Dynamic metaprogramming, which distinguishes between code generators and static meta-programming in compiler mode. Batch generation of various codes (classes, methods, tests, etc.) to reduce repetitive operations during programming. Various Dsl,code Generator,scalfolding,project bootstraping have benefited from meta programming. Programming (programming) is an abstraction of a solution to a class of problems.
Meta-programming (meta-programming) is an abstraction of some sort of workaround.
In other words, meta-programming is an abstraction for programming.
As for the DSL part I do not agree, admittedly, the Ruby Circle DSL has a tendency to overflow, to create DSLs for DSLs, for the sake of technology and DSL, but these are not the focus. The advent of DSLs is an inevitable consequence of high abstraction, which naturally dies out of the abstract DSL.
Give some chestnuts:
ORM
I have now n entity classes and I need to persist these entity classes for storage. So I wrote n a DAO. Later found that DAO these things seem very boring, just a few steps, according to the entity class name to create a table, based on attributes to create a database field, and then delete and change. (ORM)
To solve these "similar repetitive tasks", we need some mechanism to translate one of my "meta program" into a specific program. This is the difference in the level of abstraction.
ORM Basic steps: According to the entity class class name to determine the database table name, according to the entity class attributes to determine the database field, unified Insert\delete\find\update method, according to the corresponding relationship between the property and database fields to complete data recovery and preservation. In Java, we get the class name and database fields through reflection, using generics + integration to obtain insert\delete\find\update and various public methods. The result is that you simply inherit a parent class and you can complete the DAO operation. (github-satyan/sugar:insanely easy-to-work with Android Database.) Here is an example)
grammatical analysis and lexical analysis
Grammatical analysis and morphology are also a kind of things with great similarity but different. A typical example is LEX&YACC (Flex&bison), Lex is a lexical parser, and YACC is a parser for syntax (the "parser" may be somewhat less worded). For lexical/parsing purposes, Lex accepts a. l file, Yacc accepts a. y file, and their results are generated. C code. Generate code through a DSL, which is what the compiled language does (not much for C + +, especially the new C + + standard introduces many new features, is saidcan be as convenient as dynamic language) analyzer is the essence of a finite state machine, state machine core work should be divided state, through meta programming, we can avoid writing state machine "repetitive labor" (strictly speaking should be similar labor)
An example of Ruby metaprogramming: The repeat Code of the Eraser Commissioner
You are a wipe-down Commissioner, you take over an old equipment information system, which maintains the device info and price for each computer. This data comes from an ancient data source (DataSource). So you have a bunch of similar:
Ds=datasource.new
Ds.get_mouse_info (workstation_id)
Ds.get_mouse_price (workstation_id)
Ds.get_keyboard_info (workstation_id)
Ds.get_keyboard_price (workstation_id)
Such a function has a dozen, every component of the computer has such a function.
To match the new reporting system, you need to return a packaged object that has a separate method for each part that returns a string containing the description and price. It is obvious that if you do not think of any way, in the future for a long time you have to copy, paste the code of the mire struggle.
Each method is similar, each method named XXX, first obtains the information through the Ds.get_xxx_info, then Ds.get_xxx_price obtains the price, then stitching the string ...
Solution: For Ruby, take advantage of dynamic dispatch (send) \ Dynamic creation method, even we can get introspection to obtain DataSource's methods, know what parts, and then create methods for these parts. In return, you don't have to create \ Maintain a list of parts, and if someone adds a new part to the DS class, your computer class will automatically support it.
---------------------------------------------------Explore------------------------------------------------------
For JavaScript programmers, you can still use the same pattern, introspective + add functions dynamically.
PY does not have much to say about this aspect, theory should be similar.
The trouble with Java is that you can't add methods dynamically, so you can only go back and then provide a list of parts and a string Get_info (string component) function. Get a list of parts and call functions by reflection.
In addition to generating code, the C language seems to have no other way.

ActiveRecord
All the people who used it said yes. Many of the tricks and magic in it are implemented using meta programming. In principle, there are two types of Meta-programming that can be seen at the moment, the first focusing on the re-forming of the grammar, that is, Dsl,lisp/scheme belongs to this class, and the last few years of the newly-champion Ruby belong to this faction, and even the REBOL that go farther but relatively small Language The second focus is on calculating and dispatching at compile time to achieve automatic code selection optimization for a particular scenario, which is the template for C + +. C's macro has both, but the ability is weaker. As far as I can see, the former is more recognized by the college, and the latter is more widely used in the east of C + +.

The quote in the question, I think, is about C + +, because it highlights the do part of the work at compile time. But Python's meta-programming, I've unheard of. Python 1.2 started now, I really haven't heard of Python's ability to build a DSL, let alone the so-called meta-programming. The culture of the Python community has never been a tradition of grammatical play. So the survey, it said that should be the third thing: The dynamic adjustment of class structure, essentially, is the reflection (reflection). Refer to this article on DeveloperWorks: Metaclass Programming in Python , and this article: metaprogramming 。 It is not difficult to see that the two articles are talking about a completely different topic. So the so-called Lisp and Ruby on the meta-programming is better than Python, in my opinion is a pseudo-proposition, because the two said meta-programming connotation and extension are different.

In the actual work, no matter what kind of meta-programming, I have a negative attitude. But the reason is different from the previous friend's opinion. I think meta-programming is undermining one of the basic principles of communication: the same programming language should have the same habit of communication. Building a DSL too casually makes communication between programmers more difficult. A typical example of this is REBOL, where several DSL grammars are significantly different, the cost of re-learning is too high, and they actually contribute to the divisive tendencies of the community. Idle to have nothing to do, oneself play also will forget, put in work, harm oneself.

As for the Meta-programming of the Lisp/scheme family, it is not so much better to say that the grammatical structure is too simple to make it look like a change. With this in mind, compare REBOL, which does not have much resemblance to some of the DSL syntaxes it constructs. However, for me, the simple syntax of lisp/scheme is actually my favorite Scheme: The designer of the compiler can devote more effort to running and optimizing.

Or that sentence, we write the program to solve the problem. Abstraction and expression are means, not ends. Engrossed on the head of the grammar, is the tricky head. I usually do not use this thing, mainly I like the language meta programming ability is not big. Why is Lisp and Ruby Meta-programming better than Python because they have "the ability to re-read their code at compile time or run time and then modify the recompile", such as Lisp's macros, such as Ruby's DSL, for example, F # Computation expression, for example, LINQ and expression in C # , such as the C + + template (which is far more farfetched), such as Haskell's Monad. Python doesn't have any fur.

But I think this function is not very useful, OK or don't make it. It is not clear what the meta-programming solves, but it can be said that the application of Ruby meta-programming:

1,rails is a complete achievement of Ruby's meta-programming capabilities.
The 2,ruby community has emerged from a variety of excellent tools, all borrowed the power of meta-programming.
3, in Ruby, meta programming is not special, it is programming.
The above is only for those who say that meta-programming is not a big use of those answers. Lisp's programs and data are based on list, so as long as the list structure can be generated, can be equivalent to generate code, and Lisp's really powerful macro mechanism is the runtime code expansion and evaluation.
Almost any of a slightly larger Lisp program will have some code to define macros or write with macros.

Ruby's meta-programming inherits from Lisp and Smalltalk, on the one hand, the ability to execute code dynamically through eval, and the ability to open and close scopes by constructing language closures. And there is a very concise and introspective/reflective mechanism to judge the runtime state of the program, which in turn assists in the generation of code.

C + + template meta-programming mechanism lies in the compilation period, through the template to type and data calculation to expand the generation code, so there will be very powerful and common STL (Standard Template Library) appears.

Is it possible for Python to somehow be meta-programmed (modifying meta-classes/data?). ), just not flexible enough, so few people use it, The philosophical attitude of Python determines that the community will try to stay away from meta-programming .

For examples such as Ruby's ActiveRecord, see active Record Query Interface and Rails/activerecord
The vast majority of Ruby DSLs use metaprogramming techniques, and other books: Ruby meta-programming

In-depth research, the role of meta-programming is still very large. Abstraction is more than just a hierarchy of simple code. Let's say this:
In the early days of the industrial age, this was the case:
People produce machines, machines produce products.

To the late:
Human production machines, machine production machines, machine production products.

Clearly, machine-making machines are a remarkable step forward, which has liberated the labor force greatly.


Meta-programming is similar to machine production machines, which simply means that programs can change themselves or generate new programs. This, of course, greatly frees the programmer.

Of course, in fact, before metaprogramming, programmers invented a lot of assistive tools to help themselves with programming, such as the IDE or something. Just later the programmer think the IDE is too weak, you can find the replacement jump to the reference template what, if the program can produce their own how good.

==================== Popular Science finished, the following is irresponsible imagination =====================

In fact, Meta-programming has not always been a well-defined concept, mainly meta (meta) the meaning of the word itself is very vague.

The yuan is generally understood to be more basic and more fundamental. Meta-programming is a program that is more basic than programs, that is, program generation programs. From this point of view, whether it is a C + + template, c macros,. NET emit and compiler Provider, JavaScript string concatenation and eval, and even what the Dynamic Network code generator, are program-generated programs.

But in general, to be called meta-programming or to meet certain conditions, of course, because the concept of meta-programming is not well-defined, these conditions can only be regarded as a consensus. The character of this language is considered a meta-programming, and B does not think it is a normal thing, the following list of these conditions, just stand in my view:

1, the language with meta-programming ability, must be able to produce the same programming language code language, but not in one language to produce another language program. This excludes the code generator.
2, the language with meta-programming ability, the program code generated by meta-programming, must be able to pass lexical analysis. This rule excludes the macros from C and the eval of JavaScript.
......

It can be seen that, in the end, a meta-programming, the use of different constraints can be different results. When we discuss a programming language is not possible meta-programming, condition 1 is basically can reach consensus, conditions 2 on each have their own views.


When meta-programming was first created, simply to ease the burden on programmers, the C + + template was initially just an extension of overloading. Because of the strong type, the C language must write a large stack of duplicated code for different types, overloading solves the name pollution of these duplicate codes, and generics begin to resolve the duplication of the code. But the C + + commission that group of guys obviously won't stop at generics like Anders, high-end atmosphere of the gradehas always been the pursuit of C + + efforts, so the generics have been made a template, and further, the programmer also come up happy, play out the C + + template meta-programming.

Let's write it here, Metaprogramming is writing code that can generate code. With such a layer of abstraction, you can make your program more scalable and adaptable to more unknown situations. The reflection in Java, the STL templates in C + +, and all the magical forwarding agents in Ruby are the applications of meta-programming. The success of rails was built on Ruby's powerful meta-programming, which is why rails did not choose other languages.
  • 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.