Declarative programming and imperative programming

Source: Internet
Author: User

To unify the concept first, we have two ways of programming: imperative and declarative.

We can define the difference between them as follows:

• Imperative Programming : Command "machine" How to do things, so whatever you want, it will follow your command.
• Declarative Programming : Tell the Machine what you want (what), and let the machine figure out how to do it.

Code examples for declarative programming and imperative programming:

As a simple example, let's say we want to double the values in an array.

We implement it in an imperative programming style, like this:

var numbers = [1,2,3,4,5]var doubled = [ ]for (var0; i < numbers.length; i++) {  var2 //= [2,4,6,8,10]    

We iterate through the entire array, take each element, multiply it by two, and then put the doubled value into the new array, manipulating the double array every time until all the elements have been computed.

Using the declarative programming method, we can use the Array.map function, like this:

var numbers = [1,2,3,4,5]var doubled =  Numbers.map (function (n) {  return2//= = [2,4,6,8,10] 

Map creates a new array with the current array, and each element in the new array is processed by the function (n) {return n*2}) passed into the map.

What the map function does is generalize the process of traversing the entire array directly, and let's focus on describing what we want. Note that we have a pure function in the map, it does not have any side effects (does not change the external state), it just receives a number and returns the value multiplied by two.

In some languages with functional programming features, there are other commonly used declarative function methods for the operation of list data types. For example, to ask for all the values in a list and command programming to do so:

var numbers = [1,2,3,4,5]var0  for (var0; i < numbers.length; i++) {  +=//= 15 

In declarative programming, we use the Reduce function:

var numbers = [1,2,3,4,5]var total =  Numbers.reduce (function (sum, n) {  return sum +//= +

The reduce function uses an incoming function to operate a list into a value. It takes this function as a parameter, and each element in the array is processed by it. Each invocation, the first argument (this is sum) is the result of the function's handling of the previous value, and the second parameter (n) is the current element. This way down, each new element of this process is summed into sum, and finally we get the entire array of sums.

Similarly, the reduce function induces the implementation of how we traverse the array and state management sections, providing us with a common way to combine a list into a single value. All we need to do is to indicate what we want.

Is declarative programming strange?

If you have not heard of the map and the reduce function before, your first feeling, I believe, will be like this. As programmers, we are very accustomed to pointing out how things should work. "Go through the list", "If this happens then," and "assign this new value to this variable". When we already know how to tell a machine how to do things, why do we need to learn this seemingly weird inductive pull-out function tool?

In many cases, imperative programming is useful. When we write business logic, we usually have to write imperative code, there is no possibility in our special business There is also a can be summed out the implementation of the extraction.

However, if we take the time to learn (or find) declarative parts that can be summed up, they can bring great convenience to our programming. First, I can write less code, which is a shortcut to success. And they allow us to stand on a higher level to think, to stand in the clouds and think about what we want, instead of standing in the mud and thinking about how things should be done.

Declarative programming Language: SQL

Maybe you don't understand, but there's a place where you might have used declarative programming, which is SQL.

You can think of SQL as a declarative query language for processing data. Write an application entirely in SQL? That's impossible. But it's incredibly powerful if you're dealing with an interconnected set of data.

Query statements such as the following:

from = owners.id

If we implement this logic in an imperative way:

//dogs = [{name: ' Fido ', owner_id:1}, {...}, ...]//owners = [{id:1, Name: ' Bob '}, {...}, ...]varDogswithowners = []varDog, owner for(varDi=0; Di < dogs.length; di++) {Dog=Dogs[di] for(varOi=0; Oi < owners.length; oi++) {owner=Owners[oi]if(owner && dog.owner_id = =owner.id) {Dogswithowners.push ({dog:dog, owner:owner}) }}}

I did not say that SQL is a very easy to understand language, and did not say a glance can see them, but basically still very neat.

SQL code is not only very short, not only easy to read, it also has a greater advantage. Because we're inductive, we can focus on what, and let the database help us optimize how.

Our imperative programming code will run very slowly because we need to traverse the owner of every dog in the list.

In the case of SQL, we can let the database handle how to find the data we want. If you need an index (assuming we built the index), the database knows how to use the index.

This has also made a big improvement in performance. If it has executed the same query before this time, it may be found immediately in the cache. By letting go of how, let the machine do these difficult things, we don't

You need to master the principles of the database to easily complete the task.

Declarative programming: D3.js

Another really powerful place to demonstrate declarative programming is user interface, graphics, and animation programming.

It's difficult to develop a user interface. Because of the user interaction, we want to create a nice dynamic user interaction, usually we use a lot of state declarations and many of the same functions of the generation

Code, which can actually be summed up and refined.

D3.js a very good statement. An example of an inductive refinement is a toolkit that helps us to develop interactive and animated data visualization models using JavaScript and SVG.

The first time (or 5th or even 10th time) you may have a big head when you develop the D3 program. Like SQL, D3 is a powerful common tool for visualizing data operations, and it gives you all the ways you need to say what you want.

Here's an example (I suggest you take a look at this demo). This is a D3 visual implementation that draws a circle for each object in the data array. To demonstrate this process, we add a circle per second.

The most interesting section of the code is:

//var data = [{x:5, y:10}, {x:20, y:5}]varCircles = Svg.selectall ('Circle'). Data (data) Circles.enter (). Append ('Circle'). attr ('CX', function (d) {returnd.x}). attr ('Cy', function (d) {returnd.y}). attr ('R',0). Transition (). Duration ( -). attr ('R',5)

There is no need to fully understand what this code is doing (you need some time to understand it), but the key point is:

First we collect all the circles in SVG and then bind the data array to the object.

D3 has a relational table that binds the point data to each circle. Initially we had only two points, no circles, and we used the. Enter () method to get the data points. Here, our intention is to draw a circle, the center is x and y, the initial value is 0, half a second after the transformation into a radius of 5.

Imperative programming is the abstraction of hardware operations, and programmers need to tell the computer exactly what to do with instructions.

Declarative is an important feature of functional programming, there are other features, such as higher-order functions, functions without side effect, only values without variables, recursion instead of iteration, and so on. Think

To fully master the function requires you to thoroughly refresh your mind, even forget the command-style habits, so the learning curve is steep.

But this does not prevent the "declarative" feature from being used in certain areas, because it does greatly simplify the code.

Reference:

http://www.vaikan.com/

Http://mp.weixin.qq.com/s/n_b-yUIxf9ohnYa3Iefoig

Declarative programming and imperative programming

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.