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


当前回答

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

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

其他回答

我将添加另一个在声明式/命令式编程讨论中很少出现的示例:用户界面!

在c#中,您可以使用各种技术构建UI。

在命令式端,你可以使用DirectX或OpenGL命令式地绘制按钮、复选框等。一行一行的(或者实际上是一个三角形一个三角形的)。如何绘制用户界面由您决定。

在声明端,有WPF。您只需编写一些XML(是的,是的,技术上是“XAML”),框架就会为您完成工作。你说用户界面是什么样的。如何做到这一点取决于系统。

总之,这是另一件值得思考的事情。仅仅因为一种语言是声明式或命令式的,并不意味着它没有另一种语言的某些特性。

此外,声明式编程的一个好处是,通过阅读代码通常更容易理解目的,而命令式编程则可以更好地控制执行。

要点是:

说明性->你想做什么

命令式->你想怎么做

这只是一个实际的例子,说明为什么CSS是声明式的,而JavaScript是命令式的。

假设我们有这个导航栏,用户当前正在查看“探索”选项,所以它被标记为当前选中。

<ul>
  <li class="selected">
    <p>Explore</p>
  </li>
  <li>
    <p>Suggestions</p>
  </li>
</ul>

我们希望当前选择的选项的标题是蓝色的,我们如何实现这与CSS和JavaScript?

CSS

li.selected > p {
  color: blue;
}

李在这里。Selected > p声明了我们想要属性颜色的元素的模式:蓝色;待应用。结果是“探索”用蓝色突出显示,而“建议”没有。注意,我们的代码描述了我们想要发生什么,而不是如何发生。CSS选择器引擎如何找到“探索”?我们不知道,通常也不在乎。

JavaScript

let liElements = document.getElementsByTagName("li")
for (let i = 0; i < liElements.length; i++) {
  if (liElements[i].className === "selected") {
    let children = liElements[i].childNodes
    for (let j = 0; j < children. length; j++) {
      let child = children[j]
      if (child.nodeType === Node.ELEMENT_NODE && child.tagName === "P") {
        child.setAttribute("style", "color: blue")
      }
    } 
  }
}

这段代码要长得多,也更难理解。除此之外,它将蓝色应用于所选选项,但当所选类被删除时,它永远不会取消应用它。蓝色只有在页面重新加载时才会重置。注意,在这段代码中,我们一步一步精确地指定了需要做什么以及如何做。

结论

每种编程范例都有其优点。

CSS(声明)

简洁的 作为程序员,我们不能控制CSS内核如何做我们需要的事情。这给了CSS核心开发人员在任何时候改变CSS选择器实现的机会。为什么CSS核心需要改变?也许,CSS开发人员找到了一种更快的方法来应用属性。

JavaScript(必须)

定制。我们控制代码如何实现目标的所有方面。 适合解决各种各样的问题

命令式编程 一种需要编程规程的编程语言,如C/ c++, Java, COBOL, FORTRAN, Perl和JavaScript。用这种语言编写程序的程序员必须基于数据处理和编程知识,开发出适当的操作顺序来解决问题。

声明性编程 一种不需要编写传统编程逻辑的计算机语言; 用户专注于定义输入和输出,而不是过程式编程语言(如c++或Java)中所需的程序步骤。

声明性编程的例子有CSS、HTML、XML、XSLT、RegX。

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

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

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

例如,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。

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

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