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


当前回答

这里和其他在线帖子的答案提到了以下内容:

使用声明式编程,您编写的代码描述您想要的东西,但不一定是如何得到它 您应该更喜欢声明式编程而不是命令式编程

他们没有告诉我们如何实现这一目标。为了使部分程序更具声明性,其他部分必须提供抽象来隐藏实现细节(即命令式代码)。

例如,LINQ比循环(for, while等)更具声明性,例如,你可以使用list. where()来获得一个新的过滤列表。为了实现这一点,微软已经完成了LINQ抽象背后的所有繁重工作。

事实上,函数式编程和函数式库更具有声明性的原因之一是因为它们抽象了循环和列表创建,隐藏了所有实现细节(很可能是带有循环的命令式代码)。

在任何程序中,都将同时拥有命令式代码和声明式代码,并且应该将所有命令式代码隐藏在特定于领域的抽象后面,以便程序的其他部分可以声明性地使用它们。

最后,尽管函数式编程和LINQ可以使您的程序更具声明性,但您总是可以通过提供更多的抽象来使程序更具声明性。例如:

// JavaScript example

// Least declarative
const bestProducts = [];
for(let i = 0; i < products.length; i++) {
    let product = products[i];
    if (product.rating >= 5 && product.price < 100) {
        bestProducts.push(product);
    }
}


// More declarative
const bestProducts = products.filter(function(product) {
    return product.rating >= 5 && product.price < 100;
});

// Most declarative, implementation details are hidden in a function
const bestProducts = getBestProducts();

另外,声明式编程的极端是发明新的领域特定语言(DSL):

字符串搜索:正则表达式而不是自定义命令式代码 js: JSX而不是直接的DOM操作 AWS CloudFormation:用YAML代替CLI 关系型数据库:用SQL代替旧的读写api,如ISAM或VSAM。

其他回答

声明式与命令式

编程范式是计算机编程的一种基本风格。 主要有四种范式:命令式、声明式、函数式(被认为是声明式范式的子集)和面向对象的。

Declarative programming : is a programming paradigm that expresses the logic of a computation(What do) without describing its control flow(How do). Some well-known examples of declarative domain specific languages (DSLs) include CSS, regular expressions, and a subset of SQL (SELECT queries, for example) Many markup languages such as HTML, MXML, XAML, XSLT... are often declarative. The declarative programming try to blur the distinction between a program as a set of instructions and a program as an assertion about the desired answer.

命令式编程:是一种编程范式,它用改变程序状态的语句来描述计算。命令式程序可以被视为编程命令或数学断言。

函数式编程:是一种编程范式,它将计算视为数学函数的求值,并避免状态和可变数据。它强调函数的应用,而命令式编程风格强调状态的变化。 在纯函数式语言(如Haskell)中,所有函数都没有副作用,状态更改仅表示为转换状态的函数。

下面是MSDN中命令式编程的示例,循环遍历数字1到10,并找到偶数。

var numbersOneThroughTen = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//With imperative programming, we'd step through this, and decide what we want:
var evenNumbers = new List<int>();
foreach (var number in numbersOneThroughTen)
{    if (number % 2 == 0)
    {
        evenNumbers.Add(number);
    }
}
//The following code uses declarative programming to accomplish the same thing.
// Here, we're saying "Give us everything where it's even"
var evenNumbers = numbersOneThroughTen.Where(number => number % 2 == 0);

这两个例子都产生了相同的结果,一个既不比另一个好也不比另一个差。第一个示例需要更多代码,但代码是可测试的,命令式方法让您完全控制实现细节。在第二个例子中,代码可以说更可读;然而,LINQ并不能让你控制幕后发生的事情。您必须相信LINQ将提供所请求的结果。

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

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的灵活性是多么简单……

这种差异主要与抽象的总体水平有关。对于声明式,在某些情况下,您离单个步骤太远了,以至于程序在如何获得结果方面有很大的自由度。


你可以把每一条指令都看作是连续体上的某个地方:

抽象程度:

Declarative <<=====|==================>> Imperative

声明性真实世界的例子:

图书管理员,请帮我借一本《白鲸记》。 (图书管理员可酌情选择最佳的申请方式)

现实世界的例子:

进入图书馆 查找图书组织系统(卡片目录-老派) 研究如何使用卡片目录(你也忘了,对吧) 弄清楚货架是如何标记和组织的。 弄清楚书架上的书是如何排列的。 从卡片目录和组织系统中交叉引用图书位置以查找所述书籍。 带书到退房系统。 借书。

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岁

已经添加了很多代码示例,所以我不再添加另一个。 相反,我将尝试用一种我认为比大多数流行的定义更清楚地解释这两种方法之间的区别:

声明性方法侧重于特定算法的目的,这通常隐藏了算法本身。 命令式方法侧重于特定目的的算法,通常隐藏了目的本身。