函数式编程、声明式编程和命令式编程是什么意思?
当前回答
简而言之:
命令式语言指定了计算机按顺序执行的一系列指令(做这个,然后做那个)。
声明性语言声明了一组规则,说明哪些输入应该产生哪些输出(例如:如果你有A,那么结果就是B).引擎会将这些规则应用于输入,并给出输出。
函数式语言声明了一组数学/逻辑函数,这些函数定义了如何将输入转换为输出。如。F (y) = y * y.它是一种声明性语言。
其他回答
命令式——表达式描述要执行的动作序列(关联的)
声明性——表达式是对程序行为做出贡献的声明(关联、交换、幂等、单调)
函数式表达式的值仅为效果;语义支持等式推理
当务之急:如何实现我们的目标
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
对于这些并没有明确客观的定义。以下是我对它们的定义:
命令式——重点是计算机应该采取什么步骤,而不是计算机将会做什么(例如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
我认为你的分类是不正确的。有两种相反的类型,命令式和声明式。函数式只是声明式的一个子类型。顺便说一句,维基百科也说了同样的事实。