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


当前回答

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

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

其他回答

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

   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

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

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

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

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

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

简而言之:

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

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

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

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

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

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

这里有一些关于所提到的“类型”的好答案。

我还提供了一些额外的、更“奇特”的概念,通常与函数式编程人群有关:

领域特定语言或DSL编程:创建一种新的语言来处理手头的问题。 元编程:当你的程序编写其他程序时。 进化编程:你构建一个系统,它可以不断地自我改进,或者不断地生成更好的子程序。