Friday, March 6, 2015

declarative and imperative programming

Declarative programming is when you write your code in such a way that it describes what you want to do, and not how you want to do it. It is left up to the compiler to figure out the how. Examples of declarative programming languages are SQL and Prolog

Reference: http://stackoverflow.com/questions/129628/what-is-declarative-programming


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<in  t> { 1, 2, 3, 4, 5 };

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

List<int> results = new List<int&g  t;();  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);        
Reference: http://stackoverflow.com/questions/1784664/what-is-the-difference-between-declarative-and-imperative-programming


http://latentflip.com/imperative-vs-declarative/

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.