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


当前回答

命令式——表达式描述要执行的动作序列(关联的)

声明性——表达式是对程序行为做出贡献的声明(关联、交换、幂等、单调)

函数式表达式的值仅为效果;语义支持等式推理

其他回答

对于这些并没有明确客观的定义。以下是我对它们的定义:

命令式——重点是计算机应该采取什么步骤,而不是计算机将会做什么(例如C, c++, Java)。

声明性——重点是计算机应该做什么,而不是它应该如何做(例如SQL)。

函数式——声明性语言的子集,非常注重递归

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

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

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

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

命令式的例子

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

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

命令式编程是指任何一种编程风格,其中你的程序是由描述计算机执行的操作如何发生的指令构成的。

声明式编程是指任何一种编程风格,其中你的程序是对问题或解决方案的描述,但没有显式地说明如何完成工作。

函数式编程是通过计算函数和函数的函数来编程。函数式编程(严格定义)是指通过定义无副作用的数学函数来编程,因此它是一种声明式编程,但它不是唯一的声明式编程。

逻辑编程(例如在Prolog中)是另一种形式的声明式编程。它包括通过决定一个逻辑语句是否为真(或是否可以满足它)来计算。程序通常是一系列事实和规则——即描述,而不是一系列指令。

术语重写(例如CASL)是声明式编程的另一种形式。它涉及代数项的符号变换。它完全不同于逻辑编程和函数式编程。

当务之急:如何实现我们的目标

   Take the next customer from a list.
   If the customer lives in Spain, show their details.
   If there are more customers in the list, go to the beginning

声明性:我们想要达到的目标

   Show customer details of every customer living in Spain