Functional Programming vs. Imperative Programming

来源:互联网 发布:中走丝编程软件 编辑:程序博客网 时间:2024/04/29 11:28

The functional programming paradigm was explicitly created to support a pure functional approach to problem solving. Functional programming is a form of declarative programming.In contrast, most mainstream languages, including object-orientedprogramming (OOP) languages such as C#, Visual Basic, C++, and Java –,were designed to primarily support imperative (procedural) programming.

With an imperative approach, a developer writes code that describes inexacting detail the steps that the computer must take to accomplish thegoal. This is sometimes referred to as algorithmicprogramming. In contrast, a functional approach involves composing theproblem as a set of functions to be executed. You define carefully theinput to each function, and what each function returns. The followingtable describes some of the general differences between these twoapproaches.

Characteristic

Imperative approach

Functional approach

Programmer focus

How to perform tasks (algorithms) and how to track changes in state.

What information is desired and what transformations are required.

State changes

Important.

Non-existent.

Order of execution

Important.

Low importance.

Primary flow control

Loops, conditionals, and function (method) calls.

Function calls, including recursion.

Primary manipulation unit

Instances of structures or classes.

Functions as first-class objects and data collections.

Although most languages were designed to support a specific programmingparadigm, many general languages are flexible enough to supportmultiple paradigms. For example, most languages that contain functionpointers can be used to credibly support functional programming.Furthermore, in C# 3.0 and Visual Basic 9.0, explicit languageextensions have been added to support functional programming, includinglambda expressions and type inference. LINQ technology is a form ofdeclarative, functional programming.