Common programming paradigms include imperative which allows side effects, functional which disallows side effects, declarative which does not state the order in which operations execute
(翻译:常见的编程语言类型包括允许有副作用的命令式编程,不允许副作用的函数式编程和不描述操作执行顺序的声明式编程)
A programming paradigm is a fundamental style of computer programming. There are four main paradigms: imperative, declarative, functional (which is considered a subset of the declarative paradigm) and object-oriented.
Declarative programming : is a programming paradigm that expresses the logic of a computation(What do) without describing its control flow(How do). Some well-known examples of declarative domain specific languages (DSLs) include CSS, regular expressions, and a subset of SQL (SELECT queries, for example) Many markup languages such as HTML, MXML, XAML, XSLT… are often declarative. The declarative programming try to blur the distinction between a program as a set of instructions and a program as an assertion about the desired answer.
Imperative programming : is a programming paradigm that describes computation in terms of statements that change a program state. The declarative programs can be dually viewed as programming commands or mathematical assertions.
Functional programming : is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. In a pure functional language, such as Haskell, all functions are without side effects, and state changes are only represented as functions that transform the state.
( 出处:维基百科)
翻译总结:
编程语言主要有四种类型
举个简单的例子,了解三者区别
1.现有这样一个数学表达式
(1+2) * 3 / 4
命令式编程可能会这样写
var a = 1 + 2;
var b = a * 3;
var c = b / 4;
函数式编程如下写法
divide(multiply(add(1, 2), 3), 4)
函数式编程是声明式的一种类型,声明式强调目标而不是具体过程。
我们用命令式编程风格实现,像下面这样:
var numbers = [1,2,3,4,5]
var doubled = []
for(var i = 0; i < numbers.length; i++) {
var newNumber = numbers[i] * 2
doubled.push (newNumber)
}
console.log (doubled) //=> [2,4,6,8,10]
我们直接遍历整个数组,取出每个元素,乘以二,然后把翻倍后的值放入新数组,每次都要操作这个双倍数组,直到计算完所有元素。
而使用声明式编程方法,我们可以用 Array.map 函数,像下面这样:
var numbers = [1,2,3,4,5]
var doubled = numbers.map (function (n) {
return n * 2
})
console.log (doubled) //=> [2,4,6,8,10]
map利用当前的数组创建了一个新数组,新数组里的每个元素都是经过了传入map的函数(这里是function (n) { return n*2 })的处理。
map函数所做的事情是将直接遍历整个数组的过程归纳抽离出来,让我们专注于描述我们想要的是什么(what)。注意,我们传入map的是一个纯函数;它不具有任何副作用(不会改变外部状态),它只是接收一个数字,返回乘以二后的值。
参考文章
1.声明式编程和命令式编程的比较
2.阮一峰的函数编程初探文章