我一直在网上搜索声明式编程和命令式编程的定义,希望能给我一些启发。然而,我发现在一些资源中使用的语言令人生畏——例如在维基百科。 有没有人可以给我举一个现实世界的例子,让我对这个主题有一些了解(也许是c#)?


当前回答

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.

卡尔弗特,C库尔卡尼,D(2009)。LINQ至关重要。艾迪森·韦斯利48岁

其他回答

再举一个手机应用开发的例子。在iOS和Android中,我们有界面构建器,在那里我们可以定义应用程序的UI。

使用这些生成器绘制的UI本质上是声明性的,我们可以在其中拖放组件。实际的绘图发生在框架和系统下面,由框架和系统执行。

但我们也可以在代码中画出整个组件,这在本质上是必要的。

此外,一些新语言,如Angular JS,专注于以声明方式设计ui,我们可能会看到许多其他语言提供同样的支持。就像Java在Java swing或Java FX中没有任何好的声明性方法来绘制本地桌面应用程序,但在不久的将来,他们可能会这样做。

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.

卡尔弗特,C库尔卡尼,D(2009)。LINQ至关重要。艾迪森·韦斯利48岁

这里借用菲利普·罗伯茨的一句话:

命令式编程告诉机器如何做某事(导致你想要发生的事情) 声明性编程告诉机器你想要发生什么(然后计算机找出如何去做)

两个例子:

1. 将数组中的所有数字加倍

命令式地:

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]

声明:

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. 对列表中的所有项求和

命令式地

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

以声明的方式

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

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

请注意,命令式示例涉及如何创建一个新变量,改变它,并返回新值(即,如何使某事发生),而声明式示例执行给定的输入,并根据初始输入返回新值(即,我们想要发生什么)。

声明性编程是你说你想要什么,命令式编程是你说如何得到你想要的。

一个简单的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)

第一个例子是声明性的,因为我们没有指定构建列表的任何“实现细节”。

以c#为例,一般来说,使用LINQ的结果是声明式的,因为你没有说如何获得你想要的东西;你只是在说你想说的话。你可以对SQL说同样的话。

声明式编程的一个好处是,它允许编译器做出可能比手工编写更好的代码的决定。运行SQL示例,如果您有这样的查询

SELECT score FROM games WHERE id < 100;

SQL“编译器”可以“优化”这个查询,因为它知道id是一个索引字段——或者它可能没有索引,在这种情况下,它必须遍历整个数据集。或者SQL引擎知道这是利用所有8个核心进行快速并行搜索的最佳时机。作为程序员,你不需要考虑这些条件,也不需要编写代码来处理任何特殊情况。

声明式编程和命令式编程的一个很好的c#例子是LINQ。

使用命令式编程,你一步一步地告诉编译器你想要发生什么。

例如,让我们从这个集合开始,并选择奇数:

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

在命令式编程中,我们将逐步执行这些步骤,并决定我们想要什么:

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

这里,我们说:

创建一个结果集合 逐步检查集合中的每个数字 检查数字,如果是奇数,就把它加到结果中

另一方面,在声明式编程中,你写的代码描述了你想要的东西,但不一定是如何得到它(声明你想要的结果,但不是一步一步的):

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

这里,我们说的是“把所有奇怪的东西都给我们”,而不是“遍历集合”。选中此项,如果为奇数,则将其添加到结果集合中。”

在许多情况下,代码也将是两种设计的混合,因此并不总是黑白分明的。