Can your programming language do this?

Source: Internet
Author: User

One day, you are browsing your own Code And found that there are almost the same two sections of code. They are actually the same-except for spaghetti and Chocolate Moose ).

// A small example:

Alert ("I want to eat pasta! ");
Alert ("I want to eat chocolate mousse! ");
Well, this example happens to be written in Javascript, but even if you don't understand JavaScript, you should be able to understand what it is doing.

Copying code is not good. So you created a function.

Function swedishchef (food ){
Alert ("even eat" + food + "! ");
}
Swedishchef ("Pasta ");
Swedishchef ("chocolate mousse ");
OK. This is just a very small example. I believe you can imagine a more practical example. This code has many advantages and you have heard it for tens of thousands of times: maintainability, readability, abstraction = good!

Now you notice that the other two sections of code are almost exactly the same as them. Except for one function called boomboom repeatedly, the other called putinpot repeatedly. In addition, the two codes are similar:

Alert ("Lobster ");
Putinpot ("Lobster ");
Putinpot ("water ");
Alert ("chicken ");
Boomboom ("chicken ");
Boomboom ("coconut sauce ");
Now you need to find a way to use a function as a parameter for another function. This is an important capability, because it is easier for you to write the Framework Code into a function (EMU Note: Do you still remember the template method mode ?).

Function Cook (I1, I2, f ){
Alert ("take" + I1 );
F (I1 );
F (I2 );
}
Cook ("Lobster", "water", putinpot );
Cook ("chicken", "coconut sauce", boomboom );
Let's see, we passed the function as a call parameter!

YourProgramming LanguageCan this be done?

Wait ...... If we already have the specific implementation code of putinpot and boomboom functions (and do not need to reuse them elsewhere ), so isn't it more beautiful to write them into function calls using inline syntax than to explicitly declare these two functions?

Cook ("Lobster ",
"Water ",
Function (x) {alert ("pot" + x );});
Cook ("chicken ",
"Coconut sauce ",
Function (x) {alert ("boom" + x );});
Yes, it's really convenient! Please note that I just created a function without thinking about how to name it. I just need to put it in a function with my ears.
When you think of an anonymous function as a parameter, you may think of code that performs the same operation on each element in the logarithm group.

VaR A = [1, 2, 3];
For (I = 0; I <A. length; I ++ ){
A [I] = A [I] * 2;
}
For (I = 0; I <A. length; I ++ ){
Alert (A [I]);
}
It is often necessary to do the same thing for all elements in a group, so you can write such a function to help:

Function Map (FN, ){
For (I = 0; I <A. length; I ++ ){
A [I] = FN (A [I]);
}
}
Now you can change the above:

Map (function (x) {return x * 2;}, );
Map (alert, );
Another common task is to summarize all the elements in the array in a certain way:

Function sum (){
VaR S = 0;
For (I = 0; I <A. length; I ++)
S + = A [I];
Return S;
}

Function join (){
VaR S = "";
For (I = 0; I <A. length; I ++)
S + = A [I];
Return S;
}

Alert (sum ([1, 2, 3]);
Alert (join (["A", "B", "C"]);
Sum is very similar to join. You may want to abstract them into a way to extract all elements in the arrayAlgorithmSummary of generic functions:

Function reduce (FN, A, init ){
VaR S = Init;
For (I = 0; I <A. length; I ++)
S = FN (s, A [I]);
Return S;
}

Function sum (){
Return reduce (function (a, B) {return a + B;}, A, 0 );
}

Function join (){
Return reduce (function (a, B) {return a + B;}, ,"");
}
Many early programming languages cannot do this. Some languages allow you to do this, but it is difficult (for example, C has function pointers, but you must declare and define functions elsewhere ). Object-oriented languages do not guarantee that you can do anything with functions (treat functions as objects ?).

If you want to treat a function as a Class Object, Java requires you to create an object with a single method, called an operator object. Many object-oriented languages require you to create a complete file for each Class. Development like this is really fast. If your programming statement requires you to use operator objects to encapsulate methods (instead of using methods as objects), you cannot fully understand the benefits of modern (dynamic) programming languages. Could you try to return the goods and get some money?

What are the benefits of having to write functions that do nothing but go through an array to do something for each element?

Let's look back at the map function. When you want to do something for each element in the logarithm group, you probably don't care which element is used first. Whether the execution starts from the first element or the last element, your results are the same, right? If you have two CPUs at hand, you can write code segments to make each pair of elements work, So map is twice faster.

Or, use your imagination and imagine that you have thousands of servers distributed across several data centers around the world. You have a very large array. Well, let's use our imagination to imagine that this array contains the content of the entire internet. Now, you can execute map on thousands of servers at the same time, so that each server can solve a small part of the same problem.

In this example, writing a very fast code to search for the entire Internet is actually as simple as calling the map function using a simple string searcher (operator) as a parameter.

I hope you will notice a really interesting point. If you want to change the MAP/reduce mode into a technology that is useful to everyone and can immediately come in handy to everyone, you only need a super genius to write the most important part of the Code, so that map/reduce can run on a massive parallel computer array, other old codes that have always run well in a single loop can still run correctly. The only difference is that they run n times faster than the original standalone. This means that all of them suddenly become code that can be used to solve a huge problem.

Let me try again. by abstracting the concept of "loop", you can implement the "loop" process in any way you like, this includes the ability to achieve a satisfactory synchronization of the loop iteration speed with the hardware computing capability.

You should now be able to understand why you are not satisfied with computer students who have not been learned anything except Java soon (http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html ):

Without understanding functional programming, You can't invent mapreduce, the algorithm that makes Google so massively scalable. the terms map and reduce come from lisp and functional programming. mapreduce is, in retrospect, obvious to anyone who remembers from their 6.001-equivalent programming class that purely functional programs have no side effects and are thus trivially parallelizable. the very fact that Google has Ted mapreduce, and Microsoft didn't, says something about why Microsoft is still playing catch up trying to get basic search features to work, while Google has moved on to the next problem: building SkyNet ^ H ^ h the world's largest massively parallel supercomputer. I don't think Microsoft completely understands just how far behind they are on that wave.

Without understanding functional programming, you cannot invent mapreduce, an algorithm that makes Google's computing capabilities so scalable. The concepts map and reduce are derived from the lisp language and functional programming ...... (This is another articleArticleEMU does not quite understand the ins and outs of the various statements)

I hope that you can now understand that using functions as basic (dynamic) programming languages can make you more abstract in the programming process, that is, code is refined, functions are more cohesive, reusable, and scalable. Many Google applications use the MAP/reduce mode, so they all benefit from optimization or fixing defects.

I want to explain it again. I think the most productive programming language can be abstracted at different levels. The old Fortran language used to prevent you from writing functions. C has function pointers, but they are ugly, and ugly. anonymous declarations are not allowed, and they cannot be implemented when they are used, but must be implemented elsewhere. Java allows you to use operator objects, a more ugly thing. As Steve yegge said, Java is a noun kingdom (http://steveyegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html ).

Note: I mentioned Fortran here, but I used it 27 years ago. FORTRAN has a function, and I think about the GW-BASIC language in my mind at that time. (EMU note, basic does have only the so-called sub-ProgramAnd go-sub statements only re-organize the code structure, without parameters and call stacks, so there is no real function call)

Note: The title "Can you do this in your programming language?" is not the true value of this article, I transferred this article not because the original author was able to play with the elementary skills of the language, but because it was a demonstration of the MAP/reduce model.

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.