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条回答
再贱就再见
2楼-- · 2019-01-04 04:40

From my understanding, both terms have roots in philosophy, there are declarative and imperative kinds of knowledge. Declarative knowledge are assertions of truth, statements of fact like math axioms. It tells you something. Imperative, or procedural knowledge, tells you step by step how to arrive at something. That's what the definition of an algorithm essentially is. If you would, compare a computer programming language with the English language. Declarative sentences state something. A boring example, but here's a declarative way of displaying whether two numbers are equal to each other, in Java:

public static void main(String[] args)
{
    System.out.print("4 = 4.");
}

Imperative sentences in English, on the other hand, give a command or make some sort of request. Imperative programming, then, is just a list of commands (do this, do that). Here's an imperative way of displaying whether two numbers are equal to each other or not while accepting user input, in Java:

private static Scanner input;    

public static void main(String[] args) 
{
    input = new Scanner(System.in);
    System.out.println();
    System.out.print("Enter an integer value for x: ");
    int x = input.nextInt();
    System.out.print("Enter an integer value for y: ");        
    int y = input.nextInt();

    System.out.println();
    System.out.printf("%d == %d? %s\n", x, y, x == y);
}

Essentially, declarative knowledge skips over certain elements to form a layer of abstraction over those elements. Declarative programming does the same.

查看更多
狗以群分
3楼-- · 2019-01-04 04:41

A great C# example of declarative vs. imperative programming is LINQ.

With imperative programming, you tell the compiler what you want to happen, step by step.

For example, let's start with this collection, and choose the odd numbers:

List<int> collection = new List<int> { 1, 2, 3, 4, 5 };

With imperative programming, we'd step through this, and decide what we want:

List<int> results = new List<int>();
foreach(var num in collection)
{
    if (num % 2 != 0)
          results.Add(num);
}

Here, we're saying:

  1. Create a result collection
  2. Step through each number in the collection
  3. Check the number, if it's odd, add it to the results

With declarative programming, on the other hand, you write code that describes what you want, but not necessarily how to get it (declare your desired results, but not the step-by-step):

var results = collection.Where( num => num % 2 != 0);

Here, we're saying "Give us everything where it's odd", not "Step through the collection. Check this item, if it's odd, add it to a result collection."

In many cases, code will be a mixture of both designs, too, so it's not always black-and-white.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-04 04:41

Stealing from Philip Roberts here:

  • Imperative programming tells the machine how to do something (resulting in what you want to happen)
  • Declarative programming tells the machine what you would like to happen (and the computer figures out how to do it)

Two examples:

1. Doubling all numbers in an array

Imperatively:

var numbers = [1,2,3,4,5]
var doubled = []

for(var i = 0; i < numbers.length; i++) {
  var newNumber = numbers[i] * 2
  doubled.push(newNumber)
}
console.log(doubled) //=> [2,4,6,8,10]

Declaratively:

var numbers = [1,2,3,4,5]

var doubled = numbers.map(function(n) {
  return n * 2
})
console.log(doubled) //=> [2,4,6,8,10]

2. Summing all items in a list

Imperatively

var numbers = [1,2,3,4,5]
var total = 0

for(var i = 0; i < numbers.length; i++) {
  total += numbers[i]
}
console.log(total) //=> 15

Declaratively

var numbers = [1,2,3,4,5]

var total = numbers.reduce(function(sum, n) {
  return sum + n
});
console.log(total) //=> 15

Note how the imperative examples involve creating a new variable, mutating it, and returning that new value (i.e., how to make something happen), whereas the declarative examples execute on a given input and return the new value based on the initial input (i.e., what we want to happen).

查看更多
Deceive 欺骗
5楼-- · 2019-01-04 04:45

Imperative programming requires developers to define step by step how code should be executed. To give directions in an imperative fashion, you say, “Go to 1st Street, turn left onto Main, drive two blocks, turn right onto Maple, and stop at the third house on the left.” The declarative version might sound something like this: “Drive to Sue’s house.” One says how to do something; the other says what needs to be done.

The declarative style has two advantages over the imperative style:

  • It does not force the traveler to memorize a long set of instructions.
  • It allows the traveler to optimize the route when possible.

Calvert,C Kulkarni,D (2009). Essential LINQ. Addison Wesley. 48.

查看更多
老娘就宠你
6楼-- · 2019-01-04 04:45

Imperative programming is telling the computer explicitly what to do, and how to do it, like specifying order and such

C#:

for (int i = 0; i < 10; i++)
{
    System.Console.WriteLine("Hello World!");
}

Declarative is when you tell the computer what to do, but not really how to do it. Datalog / Prolog is the first language that comes to mind in this regard. Basically everything is declarative. You can't really guarantee order.

C# is a much more imperative programming language, but certain C# features are more declarative, like Linq

dynamic foo = from c in someCollection
           let x = someValue * 2
           where c.SomeProperty < x
           select new {c.SomeProperty, c.OtherProperty};

The same thing could be written imperatively:

dynamic foo = SomeCollection.Where
     (
          c => c.SomeProperty < (SomeValue * 2)
     )
     .Select
     (
          c => new {c.SomeProperty, c.OtherProperty}
     )

(example from wikipedia Linq)

查看更多
做个烂人
7楼-- · 2019-01-04 04:46

The difference has mostly to do with the overall level of abstraction. With declarative, at some point, you're so far away from the individual steps that the program has a lot of latitude regarding how to get your result.


You could look at every piece of instruction as falling somewhere on a continuum:

Degree of abstraction:

Declarative <<=====|==================>> Imperative

Declarative Real World Example:

  1. Librarian, please check me out a copy of Moby Dick. (Librarian, at their discretion chooses the best method for performing the request)

Imperative Real World Example:

  1. Go into Library
  2. Find Book Organization System (Card Catalog - Old school)
  3. Research how to use Card Catalogs (You forgot too, right)
  4. Figure out how shelves are labeled and organized.
  5. Figure out how books are organized on a shelf.
  6. Cross-reference book location from card catalog with organization system to find said book.
  7. Take book to check-out system.
  8. Check out book.
查看更多
登录 后发表回答