[GO] can your programming language do this? (JS demonstration of Map/reduce) Go

Source: Internet
Author: User
Tags money back

A very good demonstration article about Map/reduce. If you look at this, you will understand the essence of enumerable in Prototype.js.

Through it, you can write a lot of very strange very wonderful code. Just a few lines, the function is not simple oh ~
For example, in Scriptaculous, a findall, two each, is applied at the outset. 8 lines of code, in fact, just a sentence:

$A (document.getElementsByTagName ("script")). FindAll (function (s) {
Return (s.src && s.src.match (/scriptaculous/.js (/?. *)?$/))
}). Each (function (s) {
var path = S.src.replace (/scriptaculous/.js (/?). *)? $/, ');
var includes = S.src.match (//?). *load= ([a-z,]*)/);
(includes includes[1]: ' Builder,effects,dragdrop,controls,slider '). Split (', '). each (
function (include) {Scriptaculous.require (path+include+ '. js ')});
});



Can you do this in your programming language? (Map/reduce's JS demonstration) "is as follows:

One day, you were browsing your code and found that there were two big pieces of code almost the same. In fact, they are exactly the same-except one about pasta (spaghetti) and the other about chocolate mousse (chocolate Moose).

A small example:

Alert ("I'm going to eat spaghetti!");
Alert ("I want to eat chocolate mousse!");

Well, this example happens to be written in JavaScript, but if you don't understand JavaScript, you should understand what it's doing.

Copy code is not good. So, you create a function

function Swedishchef (food) {
Alert ("I want to eat" + Food + "!");
}Swedishchef ("pasta");
Swedishchef ("Chocolate mousse");

Ok, this is just a small and small example, I believe you can imagine a more practical example. This code has a lot of advantages, you've heard it tens of thousands of times: maintainability, readability, abstraction = good!

Now you notice that there are two other pieces of code that are almost exactly the same, except for one function called Boomboom repeatedly, and the other called Putinpot. Beyond that, these two pieces of code are just as different:

alert ("Take the Lobster");
Putinpot ("lobster");
Putinpot ("Water");alert ("Take the Chicken");
Boomboom ("chicken");
Boomboom ("coconut sauce");

Now think of a way to use a function as a parameter to another function. This is an important capability because it is easier for you to write the framework code into a function (EMU Note: 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);

Look, we actually passed the function as a call parameter!

Can you do it in your programming language?

Wait a minute...... If we already have the specific implementation code for the functions of Putinpot and boomboom (and do not need to reuse them elsewhere), then writing them into function calls with inline syntax is not more beautiful than the explicit declaration of these two functions?

Cook ("lobster",
"Water",
function (x) {alert ("pot" + x);});
Cook ("Chicken",
"Coconut sauce",
function (x) {alert ("boom" + x);});

Yes, it's convenient! Notice that I've just created a function, even without thinking about how to name it, just hold it by the ear and throw it into a function.

When you think of an anonymous function as a parameter, you might think of code that would do the same for each element in the array.

var a = [n/a];For (i=0; i<a.length; i++) {
A[i] = a[i] * 2;
}For (i=0; i<a.length; i++) {
Alert (A[i]);
}

It's common to do the same thing with all the elements in the array, so you can write a function like this to help:

function Map (FN, a) {
for (i = 0; i < a.length; i++) {
A[i] = fn (a[i]);
}
}

Now you can change the above to:

Map (function (x) {return x*2;}, a);
Map (alert, a);

Another common task is to summarize all the elements in an array in a general way:

function sum (a) {
var s = 0;
for (i = 0; i < a.length; i++)
s + = A[i];
return s;
}

function Join (a) {
var s = "";
for (i = 0; i < a.length; i++)
s + = A[i];
return s;
}

Alert (sum ([+)]);
Alert (Join (["A", "B", "C"]));

Sum and join look alike, and you might want to abstract them into a generic function that summarizes all the elements in an array by an algorithm:

function reduce (FN, a, init) {
var s = init;
for (i = 0; i < a.length; i++)
s = FN (S, A[i]);
return s;
}

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

function Join (a) {
return reduce (function (A, b) {return a + B;}, A, "");
}

Many of the early programming languages couldn't do that. Some languages allow you to do it, but it is difficult (for example, C has a function pointer, but you have to declare and define functions in other places). The object-oriented language is also not sure what you can do with a function (the function is treated as an object?). )。

If you want to think of a function as a class of objects, Java requires you to create an object that has a single method, called an Operator object. Many object-oriented languages want you to create a complete file for each class, so development can be called fast. If your programming language wants you to use operator objects to wrap a method (instead of using the method itself as an object), you cannot get the benefits of modern (dynamic) programming languages. May I see if you can return some money back?

What is the benefit of not having to write a function that does 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 with each element in the array, you probably don't care which element does it first. Whether the first element is executed or the last element is executed, your results are the same, right? If you have 2 CPUs on hand, you can write a piece of code that makes them work on half of the elements, so the map is twice times faster.

Or, imagine that you have tens of thousands of servers worldwide in several data centers around the world, and you have a really big, big array, and, well, try to imagine that this array records the entire content of the Internet. Also, now you can execute the map at the same time on thousands of servers, allowing each server to solve a small part of the same problem.

So in this case, the problem of writing a very fast code to search the entire internet is just as simple as using a simple string finder (operator) as a parameter to call the map function.

Hopefully you'll notice a really interesting point, and if you want to turn the Map/reduce model into a technology that works for everyone and comes in handy for everyone, you just need a super genius to write the most important part of the code to make map/ Reduce can run on a huge parallel computer array, and then the other old ones that run well in a single loop can still run correctly, the only difference being that it's only a few times faster than the original single-machine run. This means that they are suddenly turned into code that can be used to solve a huge problem.

Let me be more verbose, by abstracting the concept of "looping," you can implement the "loop" process in any way you like, including the ability to allow loop iterations to grow at a satisfactory pace with hardware computing power.

You should now be able to understand why, in the near future,computer students who have not learned anything but Java are dissatisfied.The
( http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html) :

Without understanding functional programming, you can ' t invent MapReduce, the algorithm that makes Google so massively SCA Lable. The terms Map and Reduce come from LISP and functional programming. MapReduce are, in retrospect, obvious to anyone who remembers from their 6.001-equivalent programming class that purely fun Ctional programs has no side effects and is thus trivially parallelizable. The very fact, Google invented MapReduce, and Microsoft didn ' t, says something about what Microsoft is still playing CA tch up trying-get basic search features to work, while Google have moved on to the next problem:building skynet^h^h^h^h ^h^h the world ' s largest massively parallel supercomputer. I don ' t think Microsoft completely understands just how far behind they is on the that wave.

Without understanding functional programming, you can't invent mapreduce, the algorithm that makes Google's computing power so scalable. The two terms map and reduce are derived from Lisp language and functional programming ... (This is the content of another article, EMU is not very understanding of the various statements of the ins and outs, it is not translated)

I hope you now understand that the function as a basic type of (dynamic) programming language allows you to better abstract in the programming process, which is to make the code lean, more cohesive, more reusable and more extensible. Many Google Apps use the map/reduce model, so they can benefit from being optimized or bug-corrected by someone.

I'm going to be a little more verbose, and I think the most productive programming language is that you can be abstracted at different levels. The old Fortran language used to be the one that didn't let you write functions. C has the function pointer, but they are very ugly ugly ugly ugly ugly ugly ugly, do not allow anonymous declaration, and can not use them to achieve them and must be placed in other places to achieve. Java lets you use operator objects, a more ugly thing. As Steve Yegge said, Java is aNoun Kingdom
( http://steveyegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html).

Author Note: This is the case with Fortran, but the last time I used Fortran was 27 years ago. Fortran is a function, I was in the mind of the word was probably gw-basic language. (Emu note, basic really has only so-called subroutines and GO-SUB statements, the role is simply to reorganize the code structure, no parameters and call stacks, so there is no real function call)

Translator Note: The original author of the "Your programming language can do this" is not really the title of this article is the real value, I turn this article is not because the original author can play the primary skills of the language, but because it is a model of map/reduce.

[GO] Your programming language can do this? (JS demonstration of Map/reduce) (GO)

Related Article

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.