views:

1642

answers:

6

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 any one have a real world example that they could show me that might bring some perspective to this subject...perhaps in c#

thanks

+17  A: 

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.

Mark Rushakoff
That Python example IS NOT declarative.
Juanjo Conti
Prolog is a declarative programming language.
Juanjo Conti
@Juanjo: It **IS** decalarative.
missingfaktor
+23  A: 

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.

Reed Copsey
Your answer as far as "declarative vs imperative" programming is fine. Your code to check for oddness is deeply flawed. This code does NOT check for oddness. Can you find the bug?
Eric Lippert
Yeah, it only checks for positive odd numbers -- I'll fix.
Reed Copsey
+1. However, you first mention LINQ, but what has the examples to do with that?
Zano
collection.Where is using the declarative LINQ extension methods. It's not using the C# language features, but rather the declarative API. I did not want to mix messages here, which is why I avoided the language additions built on top of the declarative methods.
Reed Copsey
+1  A: 

In computer science, declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow.

From http://en.wikipedia.org/wiki/Declarative_programming

in a nutshell the declarative language is simpler because it lacks the complexity of control flow ( loops, if statements, etc. )

A good comparison is the ASP.Net 'code-behind' model. You have declarative '.ASPX' files and then the imperative 'ASPX.CS' code files. I often find that if I can do all I need in the declarative half of the script a lot more people can follow what's being done.

kervin
+2  A: 

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)

McKay
You have a typo: The linq statements are declarative, not imperitive (You have "C# features are more imperative, like Linq" should read declarative.
Reed Copsey
+1  A: 

I'll add another example that rarely pops up in declarative/imperative programming discussion: the User Interface!

In C#, you can build an UI using various technologies.

On the imperative end, you could use DirectX or OpenGL to very imperatively draw your buttons, checkboxes, etc... line-by-line (or really, triangle by triangle). It is up to you to say how to draw the user interface.

At the declarative end, you have WPF. You basically write some XML (yeah, yeah, "XAML" technically) and the framework does the work for you. You say what the user interface looks like. It is up to the system to figure out how to do it.

Anyway, just another thing to think about. Just because one language is declarative or imperative does not mean that it doesn't have certain features of the other.

Also, one benefit of declarative programming is that purpose is usually more easily understood from reading the code whereas imperative gives you finer control over execution.

The gist of it all:

Declarative -> what you want done

Imperative -> how you want it done

Erich Mirabal
A: 

example in java or c,c+=

Rakesh
You should post this as a separate question.
missingfaktor