函数式编程、声明式编程和命令式编程是什么意思?


当前回答

现在,新的焦点是:我们需要旧的分类吗?

命令式/声明式/函数式在过去很好地分类了泛型语言,但是现在所有的“大语言”(如Java、Python、Javascript等)都有一些选项(通常是框架)来表达其主要关注点(通常是命令式)之外的“其他关注点”,并表达并行进程、声明式函数、lambdas等。

所以这个问题的一个很好的变体是“今天对框架进行分类的优点是什么?” ... 一个重要的方面是我们可以标记为“编程风格”……

重点研究数据与算法的融合

这是一个很好的例子。你可以在维基百科上读到jQuery,

jQuery的一系列核心特性——DOM元素选择、遍历和操作——由它的选择器引擎(…)支持,创建了一种新的“编程风格”,融合了算法和DOM数据结构

因此jQuery是关注“新编程风格”的最佳(流行)例子,它不仅是面向对象的,而且是“融合算法和数据结构”。jQuery有点像电子表格,但不是“面向单元格”,是“面向dom节点”…比较本文中的主要风格:

No fusion: in all "big languages", in any Functional/Declarative/Imperative expression, the usual is "no fusion" of data and algorithm, except by some object-orientation, that is a fusion in strict algebric structure point of view. Some fusion: all classic strategies of fusion, in nowadays have some framework using it as paradigm... dataflow, Event-driven programming (or old domain specific languages as awk and XSLT)... Like programming with modern spreadsheets, they are also examples of reactive programming style. Big fusion: is "the jQuery style"... jQuery is a domain specific language focusing on "fusing algorithms and DOM-data-structures". PS: other "query languages", as XQuery, SQL (with PL as imperative expression option) are also data-algorith-fusion examples, but they are islands, with no fusion with other system modules... Spring, when using find()-variants and Specification clauses, is another good fusion example.

其他回答

命令式编程:告诉“机器”如何做某事,结果你想发生的事情就会发生。

声明式编程:告诉“机器”你想要发生什么,然后让计算机想出如何去做。

命令式的例子

function makeWidget(options) {
    const element = document.createElement('div');
    element.style.backgroundColor = options.bgColor;
    element.style.width = options.width;
    element.style.height = options.height;
    element.textContent = options.txt;

    return element;
}

声明性的例子

function makeWidget(type, txt) {
    return new Element(type, txt);
}

注:区别不在于简洁、复杂或抽象。如前所述,区别在于如何做和做什么。

因为我写了我之前的答案,我制定了一个声明性属性的新定义,下面引用了它。我还将命令式编程定义为对偶属性。

这个定义比我在之前的回答中提供的定义更优越,因为它更简洁,更普遍。但它可能更难以理解,因为适用于编程和一般生活的不完备定理的含义对人类来说是很难理解的。

引用的定义解释讨论了纯函数式编程在声明式编程中所扮演的角色。

所有外来的编程类型都符合以下声明式和命令式的分类,因为下面的定义声称它们是二元的。

Declarative vs. Imperative The declarative property is weird, obtuse, and difficult to capture in a technically precise definition that remains general and not ambiguous, because it is a naive notion that we can declare the meaning (a.k.a semantics) of the program without incurring unintended side effects. There is an inherent tension between expression of meaning and avoidance of unintended effects, and this tension actually derives from the incompleteness theorems of programming and our universe. It is oversimplification, technically imprecise, and often ambiguous to define declarative as “what to do” and imperative as “how to do”. An ambiguous case is the “what” is the “how” in a program that outputs a program— a compiler. Evidently the unbounded recursion that makes a language Turing complete, is also analogously in the semantics— not only in the syntactical structure of evaluation (a.k.a. operational semantics). This is logically an example analogous to Gödel's theorem— “any complete system of axioms is also inconsistent”. Ponder the contradictory weirdness of that quote! It is also an example that demonstrates how the expression of semantics does not have a provable bound, thus we can't prove2 that a program (and analogously its semantics) halt a.k.a. the Halting theorem. The incompleteness theorems derive from the fundamental nature of our universe, which as stated in the Second Law of Thermodynamics is “the entropy (a.k.a. the # of independent possibilities) is trending to maximum forever”. The coding and design of a program is never finished— it's alive!— because it attempts to address a real world need, and the semantics of the real world are always changing and trending to more possibilities. Humans never stop discovering new things (including errors in programs ;-). To precisely and technically capture this aforementioned desired notion within this weird universe that has no edge (ponder that! there is no “outside” of our universe), requires a terse but deceptively-not-simple definition which will sound incorrect until it is explained deeply. Definition: The declarative property is where there can exist only one possible set of statements that can express each specific modular semantic. The imperative property3 is the dual, where semantics are inconsistent under composition and/or can be expressed with variations of sets of statements. This definition of declarative is distinctively local in semantic scope, meaning that it requires that a modular semantic maintain its consistent meaning regardless where and how it's instantiated and employed in global scope. Thus each declarative modular semantic should be intrinsically orthogonal to all possible others— and not an impossible (due to incompleteness theorems) global algorithm or model for witnessing consistency, which is also the point of “More Is Not Always Better” by Robert Harper, Professor of Computer Science at Carnegie Mellon University, one of the designers of Standard ML. Examples of these modular declarative semantics include category theory functors e.g. the Applicative, nominal typing, namespaces, named fields, and w.r.t. to operational level of semantics then pure functional programming. Thus well designed declarative languages can more clearly express meaning, albeit with some loss of generality in what can be expressed, yet a gain in what can be expressed with intrinsic consistency. An example of the aforementioned definition is the set of formulas in the cells of a spreadsheet program— which are not expected to give the same meaning when moved to different column and row cells, i.e. cell identifiers changed. The cell identifiers are part of and not superfluous to the intended meaning. So each spreadsheet result is unique w.r.t. to the cell identifiers in a set of formulas. The consistent modular semantic in this case is use of cell identifiers as the input and output of pure functions for cells formulas (see below). Hyper Text Markup Language a.k.a. HTML— the language for static web pages— is an example of a highly (but not perfectly3) declarative language that (at least before HTML 5) had no capability to express dynamic behavior. HTML is perhaps the easiest language to learn. For dynamic behavior, an imperative scripting language such as JavaScript was usually combined with HTML. HTML without JavaScript fits the declarative definition because each nominal type (i.e. the tags) maintains its consistent meaning under composition within the rules of the syntax. A competing definition for declarative is the commutative and idempotent properties of the semantic statements, i.e. that statements can be reordered and duplicated without changing the meaning. For example, statements assigning values to named fields can be reordered and duplicated without changed the meaning of the program, if those names are modular w.r.t. to any implied order. Names sometimes imply an order, e.g. cell identifiers include their column and row position— moving a total on spreadsheet changes its meaning. Otherwise, these properties implicitly require global consistency of semantics. It is generally impossible to design the semantics of statements so they remain consistent if randomly ordered or duplicated, because order and duplication are intrinsic to semantics. For example, the statements “Foo exists” (or construction) and “Foo does not exist” (and destruction). If one considers random inconsistency endemical of the intended semantics, then one accepts this definition as general enough for the declarative property. In essence this definition is vacuous as a generalized definition because it attempts to make consistency orthogonal to semantics, i.e. to defy the fact that the universe of semantics is dynamically unbounded and can't be captured in a global coherence paradigm. Requiring the commutative and idempotent properties for the (structural evaluation order of the) lower-level operational semantics converts operational semantics to a declarative localized modular semantic, e.g. pure functional programming (including recursion instead of imperative loops). Then the operational order of the implementation details do not impact (i.e. spread globally into) the consistency of the higher-level semantics. For example, the order of evaluation of (and theoretically also the duplication of) the spreadsheet formulas doesn't matter because the outputs are not copied to the inputs until after all outputs have been computed, i.e. analogous to pure functions. C, Java, C++, C#, PHP, and JavaScript aren't particularly declarative. Copute's syntax and Python's syntax are more declaratively coupled to intended results, i.e. consistent syntactical semantics that eliminate the extraneous so one can readily comprehend code after they've forgotten it. Copute and Haskell enforce determinism of the operational semantics and encourage “don't repeat yourself” (DRY), because they only allow the pure functional paradigm. 2 Even where we can prove the semantics of a program, e.g. with the language Coq, this is limited to the semantics that are expressed in the typing, and typing can never capture all of the semantics of a program— not even for languages that are not Turing complete, e.g. with HTML+CSS it is possible to express inconsistent combinations which thus have undefined semantics. 3 Many explanations incorrectly claim that only imperative programming has syntactically ordered statements. I clarified this confusion between imperative and functional programming. For example, the order of HTML statements does not reduce the consistency of their meaning.


编辑:我在Robert Harper的博客上发表了以下评论:

in functional programming ... the range of variation of a variable is a type Depending on how one distinguishes functional from imperative programming, your ‘assignable’ in an imperative program also may have a type placing a bound on its variability. The only non-muddled definition I currently appreciate for functional programming is a) functions as first-class objects and types, b) preference for recursion over loops, and/or c) pure functions— i.e. those functions which do not impact the desired semantics of the program when memoized (thus perfectly pure functional programming doesn't exist in a general purpose denotational semantics due to impacts of operational semantics, e.g. memory allocation). The idempotent property of a pure function means the function call on its variables can be substituted by its value, which is not generally the case for the arguments of an imperative procedure. Pure functions seem to be declarative w.r.t. to the uncomposed state transitions between the input and result types. But the composition of pure functions does not maintain any such consistency, because it is possible to model a side-effect (global state) imperative process in a pure functional programming language, e.g. Haskell's IOMonad and moreover it is entirely impossible to prevent doing such in any Turing complete pure functional programming language. As I wrote in 2012 which seems to the similar consensus of comments in your recent blog, that declarative programming is an attempt to capture the notion that the intended semantics are never opaque. Examples of opaque semantics are dependence on order, dependence on erasure of higher-level semantics at the operational semantics layer (e.g. casts are not conversions and reified generics limit higher-level semantics), and dependence on variable values which can not be checked (proved correct) by the programming language. Thus I have concluded that only non-Turing complete languages can be declarative. Thus one unambiguous and distinct attribute of a declarative language could be that its output can be proven to obey some enumerable set of generative rules. For example, for any specific HTML program (ignoring differences in the ways interpreters diverge) that is not scripted (i.e. is not Turing complete) then its output variability can be enumerable. Or more succinctly an HTML program is a pure function of its variability. Ditto a spreadsheet program is a pure function of its input variables. So it seems to me that declarative languages are the antithesis of unbounded recursion, i.e. per Gödel's second incompleteness theorem self-referential theorems can't be proven. Lesie Lamport wrote a fairytale about how Euclid might have worked around Gödel's incompleteness theorems applied to math proofs in the programming language context by to congruence between types and logic (Curry-Howard correspondence, etc).

声明性编程是通过在输入和输出之间表达一些永恒的逻辑来编程,例如,在伪代码中,下面的例子将是声明性的:

def factorial(n):
  if n < 2:
    return 1
  else:
    return factorial(n-1)

output = factorial(argvec[0])

We just define a relationship called the 'factorial' here, and defined the relationship between the output and the input as the that relationship. As should be evident here, about any structured language allows declarative programming to some extend. A central idea of declarative programming is immutable data, if you assign to a variable, you only do so once, and then never again. Other, stricter definitions entail that there may be no side-effects at all, these languages are some times called 'purely declarative'.

在命令式风格中,同样的结果将是:

a = 1
b = argvec[0]
while(b < 2):
  a * b--

output = a

在这个例子中,我们没有在输入和输出之间表达永恒的静态逻辑关系,我们手动更改内存地址,直到其中一个保存所需的结果。很明显,所有语言在某种程度上都允许声明性语义,但并非所有语言都允许命令式语义,一些“纯”声明性语言允许副作用和突变。

Declarative languages are often said to specify 'what must be done', as opposed to 'how to do it', I think that is a misnomer, declarative programs still specify how one must get from input to output, but in another way, the relationship you specify must be effectively computable (important term, look it up if you don't know it). Another approach is nondeterministic programming, that really just specifies what conditions a result much meet, before your implementation just goes to exhaust all paths on trial and error until it succeeds.

纯声明性语言包括Haskell和Pure Prolog。从一种到另一种的比例可以是:Pure Prolog, Haskell, OCaml, Scheme/Lisp, Python, Javascript, C——,Perl, PHP, c++, Pascall, C, Fortran, Assembly

命令式和声明式描述了两种相反的编程风格。命令式是传统的“循序渐进”方法,而声明式则更多地是“这就是我想要的,现在你来研究如何去做”。

这两种方法贯穿于整个编程过程——即使使用相同的语言和相同的程序。一般来说,声明式方法被认为是更可取的,因为它使程序员不必指定如此多的细节,同时也减少了出现错误的机会(如果您描述了您想要的结果,并且一些经过良好测试的自动流程可以从该结果向后工作以定义步骤,那么您可能希望事情比手工指定每个步骤更可靠)。

另一方面,命令式方法为您提供了更多的低级控制——这是编程的“微观管理方法”。这可以让程序员利用有关问题的知识来给出更有效的答案。因此,程序的某些部分以声明式的风格编写并不罕见,但对速度至关重要的部分则更加必要。

as you might imagine, the language you use to write a program affects how declarative you can be - a language that has built-in "smarts" for working out what to do given a description of the result is going to allow a much more declarative approach than one where the programmer needs to first add that kind of intelligence with imperative code before being able to build a more declarative layer on top. so, for example, a language like prolog is considered very declarative because it has, built-in, a process that searches for answers.

so far, you'll notice that i haven't mentioned functional programming. that's because it's a term whose meaning isn't immediately related to the other two. at its most simple, functional programming means that you use functions. in particular, that you use a language that supports functions as "first class values" - that means that not only can you write functions, but you can write functions that write functions (that write functions that...), and pass functions to functions. in short - that functions are as flexible and common as things like strings and numbers.

it might seem odd, then, that functional, imperative and declarative are often mentioned together. the reason for this is a consequence of taking the idea of functional programming "to the extreme". a function, in it's purest sense, is something from maths - a kind of "black box" that takes some input and always gives the same output. and that kind of behaviour doesn't require storing changing variables. so if you design a programming language whose aim is to implement a very pure, mathematically influenced idea of functional programming, you end up rejecting, largely, the idea of values that can change (in a certain, limited, technical sense).

如果你这样做——如果你限制变量的改变方式——那么你几乎会意外地迫使程序员编写更具声明性的程序,因为命令式编程的很大一部分是描述变量如何改变,而你再也不能这样做了!因此,函数式编程——特别是用函数式语言编程——倾向于给出更多的声明性代码。

总结一下:

命令式和声明式是两种相反的编程风格(鼓励这些风格的编程语言使用相同的名称) 函数式编程是一种编程风格,其中函数变得非常重要,因此,更改值变得不那么重要。在值中指定更改的有限能力迫使使用更声明性的风格。

因此,“函数式编程”通常被描述为“声明式的”。

简而言之:

命令式语言指定了计算机按顺序执行的一系列指令(做这个,然后做那个)。

声明性语言声明了一组规则,说明哪些输入应该产生哪些输出(例如:如果你有A,那么结果就是B).引擎会将这些规则应用于输入,并给出输出。

函数式语言声明了一组数学/逻辑函数,这些函数定义了如何将输入转换为输出。如。F (y) = y * y.它是一种声明性语言。