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


当前回答

声明式编程和命令式编程的一个很好的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);

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

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

其他回答

声明性程序只是它的一些或多或少的“通用”命令式实现/虚拟机的数据。

pluses: specifying just a data, in some hardcoded (and checked) format, is simpler and less error-prone than specifying variant of some imperative algorithm directly. some complex specifications just cant be written directly, only in some DSL form. best and freq used in DSLs data structures is sets and tables. because you not have dependencies between elements/rows. and when you havent dependencies you have freedom to modify and ease of support. (compare for example modules with classes - with modules you happy and with classes you have fragile base class problem) all goods of declarativeness and DSL follows immediately from benefits of that data structures (tables and sets). another plus - you can change implementation of declarative language vm, if DSL is more-or-less abstract (well designed). make parallel implementation, for example. or port it to other os etc. all good specifed modular isolating interfaces or protocols gives you such freedom and easyness of support.

缺点: 你猜对了。一般的(通过DSL参数化的)命令式算法/虚拟机实现可能比特定的算法慢和/或占用内存。在某些情况下。 如果这种情况很罕见,那就忘了它吧,让它慢慢来。如果这种情况经常发生,你总是可以扩展你的DSL/vm。某个能减缓其他案件的地方,当然…

P.S.框架介于DSL和命令式之间。作为所有的折中方案……他们结合了缺点,而不是优点。它们不是那么安全,也不是那么快:)看看万事通haskell——它介于强大的简单ML和灵活的元程序Prolog之间……真是个怪物。你可以把Prolog看作一个Haskell,它只包含布尔函数/谓词。它对Haskell的灵活性是多么简单……

我只是想知道为什么没有人提到Attribute类是c#中的声明性编程工具。本页最流行的回答是将LINQ作为一种声明性编程工具。

根据维基百科

常见的声明性语言包括数据库查询语言 (如SQL, XQuery),正则表达式,逻辑编程, 功能编程和配置管理系统。

所以LINQ作为一个函数式语法,绝对是一个声明性的方法,但是c#中的Attribute类作为一个配置工具,也是声明性的。这里有一个很好的起点来阅读更多关于它的内容:c#属性编程的快速概述

我喜欢剑桥一门课程的解释和他们的例子:

声明性-指定要做什么,而不是如何做 例如:HTML描述的是什么应该出现在网页上,而不是它应该如何在屏幕上绘制 命令式-同时指定“什么”和“如何” int x;-什么(陈述性的) x = x + 1;——如何

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

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

两个例子:

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

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

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.");
}

另一方面,英语中的祈使句给出命令或提出某种请求。因此,命令式编程只是一个命令列表(做这个,做那个)。下面是在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);
}

从本质上讲,声明性知识跳过某些元素,在这些元素之上形成一个抽象层。声明式编程也是如此。