Can you do this in your programming language? _javascript Tips

Source: Internet
Author: User
Tags abstract money back
One day, you're browsing through your code and you find that there are two large pieces of code almost the same. In fact, they are exactly the same--except for one about pasta (spaghetti) and the other about chocolate mousse (chocolate moose).

A small example:

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

Bad copy code. So, you create a function

function Swedishchef (food) {
Alert ("I want to eat" + Food + "!");
}
Swedishchef ("spaghetti");
Swedishchef ("Chocolate mousse");
Ok, this is just a very 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 like them, except for a function called Boomboom repeatedly, another called Putinpot. In addition, the two pieces of code are no different:

Alert ("Take lobster");
Putinpot ("lobster");
Putinpot ("Water");
Alert ("Take the Chicken");
Boomboom ("chicken");
Boomboom ("coconut sauce");
Now think of a way that you can use a function as an argument to another function. This is an important ability because it's easier to write the framework code as a function (EMU Note: Remember 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 with your programming language?

Wait a minute...... If we already have the concrete implementation code for the functions of Putinpot and boomboom (and we don't need to reuse them elsewhere), is it more beautiful to write them into function calls with inline syntax than explicit declarations?

Cook ("Lobster",
"Water",
function (x) {alert ("pot" + x);});
Cook ("Chicken",
"Coconut sauce,"
function (x) {alert ("boom" + x);});
Yes, that's convenient! Notice that I've just created a function that doesn't even have to consider how to name it, just throw it into a function with its ear.
When you think of an anonymous function as a parameter, you might think of code that makes the same operation for each element in the array.

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]);
}
Always do the same thing with all the elements in the array, so you can write a function to help:

function Map (FN, a) {
for (i = 0; i < a.length; i++) {
A[i] = fn (a[i]);
}
}
Now you can change the things on the top:

Map (function (x) {return x*2;}, a);
Map (alert, a);
Another common task is to sum up 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 ([1,2,3]));
Alert (Join (["A", "B", "C"]);
The sum and join look alike, and you might want to abstract them into a generic function that sums up all the elements in an array by some 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 to reduce (function (A, b) {return a + B;}, a, 0);
}

function Join (a) {
Return to reduce (function (A, b) {return a + B;}, A, "");
}
Many of the early programming languages could not do such a thing. Some languages allow you to do it, but it's difficult (for example, C has a function pointer, but you have to declare and define the function somewhere else). 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 object, Java requires you to create an object that has a single method, called an Operator object. Many object-oriented languages want you to build a complete file for each class, such as development can be really fast. If your programming language wants you to use operator objects to wrap the method (instead of using the method itself as an object), you can't get the benefits of a modern (dynamic) programming. Try to see if you can return some money back.

What is the benefit of not having to write a function that is useless except 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 to do first. Whether the first element starts or the last element executes, your results are the same, right? If you have 2 CPUs on hand, you can write code that allows them to work on half of the elements, and the map is twice times faster.

Or, imagine that you have millions of servers worldwide in several data centers around the world, you have a really big, big array, and, well, give it a second thought, and imagine that this array records the entire Internet. Also, now you can execute the map on thousands of servers and have each server solve a small part of the same problem.

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


I hope you notice a really interesting point, if you want to turn the Map/reduce model into a technology that is useful to everyone and that can come in handy for everyone, you just need a super genius to write the most important piece of code to get map/ Reduce can run on a large parallel computer array, and then the other old code, which has always worked well in a single loop, can still run correctly, with the only difference being as fast as the original single machine. This means that they all suddenly become code that can be used to solve a huge problem.

Let me be a little bit more verbose, by abstracting the concept of "loop", you can implement the "loop" process in any way you like, including the simultaneous growth that allows the loop iteration speed to remain satisfactory with the hardware computing power.

You should now be able to understand why it is not very soon to be dissatisfied with computer students who have not learned anything but Java: (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 invented 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^h^h^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 can't invent the mapreduce algorithm that makes Google's computing power so scalable. The terms map and reduce are derived from the 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, do not translate)

I hope you understand now that taking functions as basic types (dynamic) programming languages allows you to be more abstract in the process of programming, which is to make code lean, function more cohesive, more reusable, and more extensible. Many Google Apps use the Map/reduce model, so that anyone who optimizes or corrects defects can benefit from it.

I'm going to talk a little bit more, and I think the most productive programming language is that you can abstract at different levels. The old Fortran language used to be a note that doesn't allow you to write functions. C has function pointers, but they are very ugly ugly ugly ugly ugliness ugly, do not allow anonymous declaration, and can not use them when they do not have to be placed in other places to achieve. Java lets you use operator objects, a much uglier 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 the last time I used Fortran was 27 years ago. Fortran is a function, I was thinking of the code word in the brain is probably gw-basic language. (Emu note, Basic does have only so-called subroutines and go-sub statements, only to rearrange the structure of the code, 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" the title is not really the value of this article, I turned this article is not because the original author can play the Basic language skills, but because this is a map/reduce model of the demonstration.

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.