是什么声明和必要的程序之间的差异 [英] What is the difference between declarative and imperative programming

查看:125
本文介绍了是什么声明和必要的程序之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在网上搜索寻找的声明和必要程序的定义,将一些启发我。然而,在一些我已经找到了资源使用的语言是艰巨的 - 比如在维基百科
没有任何一个有一个真实的例子,他们可以告诉我,可能会带来一些观点这个主题......也许在C#。

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#.

推荐答案

声明与命令式编程的一个很好的C#示例是LINQ。

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. 创建一个结果集

  2. 通过每个步骤号集合中

  3. 检查的数量,如果是奇数,将它添加到结果

声明节目,在另一方面,你写code,描述你想要什么,但不一定如何得到它(声明您预期的效果,但不是一步-step):

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."

在很多情况下,code将两种设计的混合物,也因此它并不总是黑色和白色。

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

这篇关于是什么声明和必要的程序之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆