What is the difference between declarative and imp

2019-01-04 04:20发布

I have been searching the web looking for a definition for declarative and imperative programming that would shed some light for me. However, the language used at some of the resources that I have found is daunting - for instance at Wikipedia. Does anyone have a real-world example that they could show me that might bring some perspective to this subject (perhaps in C#)?

16条回答
\"骚年 ilove
2楼-- · 2019-01-04 04:52

Declarative programming is when you say what you want, and imperative language is when you say how to get what you want.

A simple example in Python:

# Declarative
small_nums = [x for x in range(20) if x < 5]

# Imperative
small_nums = []
for i in range(20):
    if i < 5:
        small_nums.append(i)

The first example is declarative because we do not specify any "implementation details" of building the list.

To tie in a C# example, generally, using LINQ results in a declarative style, because you aren't saying how to obtain what you want; you are only saying what you want. You could say the same about SQL.

One benefit of declarative programming is that it allows the compiler to make decisions that might result in better code than what you might make by hand. Running with the SQL example, if you had a query like

SELECT score FROM games WHERE id < 100;

the SQL "compiler" can "optimize" this query because it knows that id is an indexed field -- or maybe it isn't indexed, in which case it will have to iterate over the entire data set anyway. Or maybe the SQL engine knows that this is the perfect time to utilize all 8 cores for a speedy parallel search. You, as a programmer, aren't concerned with any of those conditions, and you don't have to write your code to handle any special case in that way.

查看更多
Fickle 薄情
3楼-- · 2019-01-04 04:53

Just to add another example in terms of mobile app development. In iOS and Android we have Interface Builders, where we can define UI of the apps.

The UI drawn using these Builders are declarative in nature, where we drag and drop the components. The actual draeing happens underneath and performed by the framework and system.

But we can also draw the whole components in code, and that is imperative in nature.

Also, some new languages like Angular JS is focussing on designing UIs declaratively and we may see a lot of other languages offering the same support. Like JAVA doesnot have any good declarative way to draw native desktop apps in JAVA swing or JAVA FX but in near future they just might.

查看更多
何必那么认真
4楼-- · 2019-01-04 04:55

All above answers and other online posts mention following:

  • With declarative programming, you write code that describes what you want, but not necessarily how to get it
  • You should prefer declarative programming over the imperative programming

What they have not told us is how to achieve it. For part of the program to be more declarative, other parts must provide the abstraction to hide the implementation details (which are the imperative codes).

  • E.g., LINQ is more declarative than loops (for, while, etc.), e.g., you can use list.Where() to get a new filtered list. For this to work, Microsoft has done all the heavy lifting behind the LINQ abstraction.

In fact, one of the reason functional programming and functional libraries are more declarative is because they have abstracted away loops and list creations, hiding all the implementation details (most likely imperative codes with loops) behind the scene.

In any program, you will always have both imperative and declarative codes, what you should aim for is to hide all imperative codes behind the abstractions, so that other parts of the program can use them declaratively.

Finally, although functional programming and LINQ can make your program more declarative, you can always make it even more declarative by providing more abstractions. For example:

// JavaScript example

// Least declarative
var bestProducts = [];
for(var i = 0; i < products.length; i++) {
    var product = products[i];
    if (product.rating >= 5 && product.price < 100) {
        bestProducts.push(product);
    }
}


// More declarative
var bestProducts = products.filter(function(product) {
    return product.rating >= 5 && product.price < 100;
});

// Most declarative, implementation details are hidden in a function
var bestProducts = getBestProducts();
查看更多
贪生不怕死
5楼-- · 2019-01-04 04:55

Imperative programming
A programming language that requires programming discipline such as C/C++, Java, COBOL, FORTRAN, Perl and JavaScript. Programmers writing in such languages must develop a proper order of actions in order to solve the problem, based on a knowledge of data processing and programming.

Declarative programming
A computer language that does not require writing traditional programming logic; Users concentrate on defining the input and output rather than the program steps required in a procedural programming language such as C++ or Java.

Declarative programming examples are CSS, HTML, XML, XSLT, RegX.

查看更多
贼婆χ
6楼-- · 2019-01-04 04:55

I just wonder why no one has mentioned Attribute classes as a declarative programming tool in C#. The popular answer of this page has just talked about LINQ as a declarative programming tool.

According to Wikipedia

Common declarative languages include those of database query languages (e.g., SQL, XQuery), regular expressions, logic programming, functional programming, and configuration management systems.

So LINQ, as a functional syntax, is definitely a declarative method, but Attribute classes in C#, as a configuration tool, are declarative too. Here is a good starting point to read more about it: Quick Overview of C# Attribute Programming

查看更多
太酷不给撩
7楼-- · 2019-01-04 05:00

Declarative vs. Imperative

A programming paradigm is a fundamental style of computer programming. There are four main paradigms: imperative, declarative, functional (which is considered a subset of the declarative paradigm) and object-oriented.

Declarative programming : is a programming paradigm that expresses the logic of a computation(What do) without describing its control flow(How do). Some well-known examples of declarative domain specific languages (DSLs) include CSS, regular expressions, and a subset of SQL (SELECT queries, for example) Many markup languages such as HTML, MXML, XAML, XSLT... are often declarative. The declarative programming try to blur the distinction between a program as a set of instructions and a program as an assertion about the desired answer.

Imperative programming : is a programming paradigm that describes computation in terms of statements that change a program state. The declarative programs can be dually viewed as programming commands or mathematical assertions.

Functional programming : is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. In a pure functional language, such as Haskell, all functions are without side effects, and state changes are only represented as functions that transform the state.

The following example of imperative programming in MSDN, loops through the numbers 1 through 10, and finds the even numbers.

var numbersOneThroughTen = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//With imperative programming, we'd step through this, and decide what we want:
var evenNumbers = new List<int>();
foreach (var number in numbersOneThroughTen)
{    if (number % 2 == 0)
    {
        evenNumbers.Add(number);
    }
}
//The following code uses declarative programming to accomplish the same thing.
// Here, we're saying "Give us everything where it's odd"
var evenNumbers = numbersOneThroughTen.Select(number => number % 2 == 0);

Both examples yield the same result, and one is neither better nor worse than the other. The first example requires more code, but the code is testable, and the imperative approach gives you full control over the implementation details. In the second example, the code is arguably more readable; however, LINQ does not give you control over what happens behind the scenes. You must trust that LINQ will provide the requested result.

查看更多
登录 后发表回答