برنامه‌نویسی تابعی

از ویکی‌پدیا، دانشنامهٔ آزاد
پرش به ناوبری پرش به جستجو

برنامه‌نویسی تابعی (به انگلیسی: Functional programming) نوعی پارادایم برنامه‌نویسی است که در آن «محاسبات» به صورت ارزش‌یابی توابع ریاضی در نظر گرفته می‌شوند.


پیوند به بیرون[ویرایش]

In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions[1] or declarations[2] instead of statements. In functional code, the output value of a function depends only on the arguments that are passed to the function, so calling a function f twice with the same value for an argument x produces the same result f(x) each time; this is in contrast to procedures depending on a local or global state, which may produce different results at different times when called with the same arguments but a different program state. Eliminating side effects, i.e., changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.


In contrast, imperative programming changes state with commands in the source code, the simplest example being assignment. Imperative programming does have subroutine functions, but these are not functions in the mathematical sense. They can have side effects that may change the value of program state. Functions without return values therefore make sense. Because of this, they lack referential transparency, i.e., the same language expression can result in different values at different times depending on the state of the executing program.[3]

Functional programming languages have largely been emphasized in academia rather than in commercial software development. However, prominent programming languages that support functional programming such as Common Lisp, Scheme,[4][5][6][7] Clojure,[8][9] Wolfram Language[10] (also known as Mathematica), Racket,[11] Erlang,[12][13][14] OCaml,[15][16] Haskell,[17][18] and F#[19][20] have been used in industrial and commercial applications by a wide variety of organizations. JavaScript, one of the world's most widely distributed languages,[21][22] has the properties of an untyped functional language,[23] in addition to imperative and object-oriented paradigms. Functional programming is also supported in some domain-specific programming languages like R (statistics),[24] J, K and Q from Kx Systems (financial analysis), XQuery/XSLT (XML),[25][26] and Opal.[27] Widespread domain-specific declarative languages like SQL and Lex/Yacc use some elements of functional programming, especially in eschewing mutable values.[28]

Programming in a functional style can also be accomplished in languages that are not specifically designed for functional programming. For example, the imperative Perl programming language has been the subject of a book describing how to apply functional programming concepts.[29] This is also true of the PHP programming language.[30] C++11, Java 8, and C# 3.0 all added constructs to facilitate the functional style. The Julia language also offers functional programming abilities. An interesting case is that of Scala[31] – it is frequently written in a functional style, but the presence of side effects and mutable state place it in a grey area between imperative and functional languages.


Lambda calculus provides a theoretical framework for describing functions and their evaluation. It is a mathematical abstraction rather than a programming language—but it forms the basis of almost all current functional programming languages. An equivalent theoretical formulation, combinatory logic, is commonly perceived as more abstract than lambda calculus and preceded it in invention. Combinatory logic and lambda calculus were both originally developed to achieve a clearer approach to the foundations of mathematics.[32]


Information Processing Language (IPL) is sometimes cited as the first computer-based functional programming language.[35] It is an assembly-style language for manipulating lists of symbols. It does have a notion of generator, which amounts to a function that accepts a function as an argument, and, since it is an assembly-level language, code can be data, so IPL can be regarded as having higher-order functions. However, it relies heavily on mutating list structure and similar imperative features.



In the 1970s, ML was created by Robin Milner at the University of Edinburgh, and David Turner initially developed the language SASL at the University of St Andrews and later the language Miranda at the University of Kent. Also in Edinburgh in the 1970s, Burstall and Darlington developed the functional language NPL.[37] NPL was based on Kleene Recursion Equations and was first introduced in their work on program transformation.[38] Burstall, MacQueen and Sannella then incorporated the polymorphic type checking from ML to produce the language Hope.[39] ML eventually developed into several dialects, the most common of which are now OCaml and Standard ML. Meanwhile, the development of Scheme, a simple lexically scoped and (impurely) functional dialect of Lisp, as described in the influential Lambda Papers and the classic 1985 textbook Structure and Interpretation of Computer Programs, brought awareness of the power of functional programming to the wider programming-languages community.




A number of concepts and paradigms are specific to functional programming, and generally foreign to imperative programming (including object-oriented programming). However, programming languages often cater to several programming paradigms, so programmers using "mostly imperative" languages may have utilized some of these concepts.[40]

First-class and higher-order functions



Higher-order functions enable partial application or currying, a technique that applies a function to its arguments one at a time, with each application returning a new function that accepts the next argument. This lets a programmer succinctly express, for example, the successor function as the addition operator partially applied to the natural number one.

Pure functions


  • If a pure function is called with arguments that cause no side-effects, the result is constant with respect to that argument list (sometimes called referential transparency), i.e., if calling the pure function again with the same arguments returns the same result. (This can enable caching optimizations such as memoization.)
  • If there is no data dependency between two pure expressions, their order can be reversed, or they can be performed in parallel and they cannot interfere with one another (in other terms, the evaluation of any pure expression is thread-safe).



Iteration (looping) in functional languages is usually accomplished via recursion. Recursive functions invoke themselves, letting an operation be repeated until it reaches the base case. Though some recursion requires maintaining a stack, tail recursion can be recognized and optimized by a compiler into the same code used to implement iteration in imperative languages. The Scheme language standard requires implementations to recognize and optimize tail recursion. Tail recursion optimization can be implemented by transforming the program into continuation passing style during compiling, among other approaches.



Strict versus non-strict evaluation



fails under strict evaluation because of the division by zero in the third element of the list. Under lazy evaluation, the length function returns the value 4 (i.e., the number of items in the list), since evaluating it does not attempt to evaluate the terms making up the list. In brief, strict evaluation always fully evaluates function arguments before invoking the function. Lazy evaluation does not evaluate function arguments unless their values are required to evaluate the function call itself.

The usual implementation strategy for lazy evaluation in functional languages is graph reduction.[42] Lazy evaluation is used by default in several pure functional languages, including Miranda, Clean, and Haskell.

Hughes 1984 argues for lazy evaluation as a mechanism for improving program modularity through separation of concerns, by easing independent implementation of producers and consumers of data streams.[43] Launchbury 1993 describes some difficulties that lazy evaluation introduces, particularly in analyzing a program's storage requirements, and proposes an operational semantics to aid in such analysis.[44] Harper 2009 proposes including both strict and lazy evaluation in the same language, using the language's type system to distinguish them.[45]

Type systems



A limited form of dependent types called generalized algebraic data types (GADT's) can be implemented in a way that provides some of the benefits of dependently typed programming while avoiding most of its inconvenience.[47] GADT's are available in the Glasgow Haskell Compiler, in OCaml (since version 4.00) and in Scala (as "case classes"), and have been proposed as additions to other languages including Java and C#.[48]

Referential transparency



Now, consider another function such as int plusone(int x) {return x+1;} is transparent, as it does not implicitly change the input x and thus has no such side effects. Functional programs exclusively use this type of function and are therefore referentially transparent.

Functional programming in non-functional languages

It is possible to use a functional style of programming in languages that are not traditionally considered functional languages.[50] For example, both D and Fortran 95 explicitly support pure functions.[51]

JavaScript, Lua[52] and Python had first class functions from their inception.[53] Amrit Prem added support to Python for "lambda", "map", "reduce", and "filter" in 1994, as well as closures in Python 2.2,[54] though Python 3 relegated "reduce" to the functools standard library module.[55] First-class functions have been introduced into other mainstream languages such as PHP 5.3, Visual Basic 9, C# 3.0, and C++11.[citation needed]

In PHP, anonymous classes, closures and lambdas are fully supported. Libraries and language extensions for immutable data structures are being developed to aid programming in the functional style.

In Java, anonymous classes can sometimes be used to simulate closures;[56] however, anonymous classes are not always proper replacements to closures because they have more limited capabilities.[57] Java 8 supports lambda expressions as a replacement for some anonymous classes.[58] However, the presence of checked exceptions in Java can make functional programming inconvenient, because it can be necessary to catch checked exceptions and then rethrow them—a problem that does not occur in other JVM languages that do not have checked exceptions, such as Scala.[citation needed]



Similarly, the idea of immutable data from functional programming is often included in imperative programming languages,[59] for example the tuple in Python, which is an immutable array.

Data structures

Purely functional data structures are often represented in a different way than their imperative counterparts.[60] For example, the array with constant access and update times is a basic component of most imperative languages, and many imperative data-structures, such as the hash table and binary heap, are based on arrays. Arrays can be replaced by maps or random access lists, which admit purely functional implementation, but have logarithmic access and update times. Therefore, purely functional data structures can be used in non-functional languages, but they may not be the most efficient tool, especially if persistence is not required.

Comparison to imperative programming



Simulating state






Efficiency issues

Functional programming languages are typically less efficient in their use of CPU and memory than imperative languages such as C and Pascal.[62] This is related to the fact that some mutable data structures like arrays have a very straightforward implementation using present hardware (which is a highly evolved Turing machine). Flat arrays may be accessed very efficiently with deeply pipelined CPUs, prefetched efficiently through caches (with no complex pointer chasing), or handled with SIMD instructions. It is also not easy to create their equally efficient general-purpose immutable counterparts. For purely functional languages, the worst-case slowdown is logarithmic in the number of memory cells used, because mutable memory can be represented by a purely functional data structure with logarithmic access time (such as a balanced tree).[63] However, such slowdowns are not universal. For programs that perform intensive numerical computations, functional languages such as OCaml and Clean are only slightly slower than C according to The Computer Language Benchmarks Game.[64] For programs that handle large matrices and multidimensional databases, array functional languages (such as J and K) were designed with speed optimizations.


Lazy evaluation may also speed up the program, even asymptotically, whereas it may slow it down at most by a constant factor (however, it may introduce memory leaks if used improperly). Launchbury 1993[44] discusses theoretical issues related to memory leaks from lazy evaluation, and O'Sullivan et al. 2008[66] give some practical advice for analyzing and fixing them. However, the most general implementations of lazy evaluation making extensive use of dereferenced code and data perform poorly on modern processors with deep pipelines and multi-level caches (where a cache miss may cost hundreds of cycles)[citation needed].

Coding styles



Printing first 10 Fibonacci numbers, using function

function fib(int $n) : int {
    return ($n === 0 || $n === 1) ? $n : fib($n - 1) + fib($n - 2);

for ($i = 0; $i <= 10; $i++) echo fib($i) . PHP_EOL;

Printing first 10 Fibonacci numbers, using closure

$fib = function(int $n) use(&$fib) : int {
    return ($n === 0 || $n === 1) ? $n : $fib($n - 1) + $fib($n - 2);

for ($i = 0; $i <= 10; $i++) echo $fib($i) . PHP_EOL;

Printing a list with first 10 Fibonacci numbers, with generators

function fib(int $n) {
    yield 0; $n--;
    yield 1; $n--;
    $second = ($first = 2) + 1;
    while ($n-- !== 0) {
        yield $first;
        [$second, $first] = [$first + $second, $second];

$fibo = fib(10);
foreach ($fibo as $value) {
    echo $value . PHP_EOL;


Printing first 10 Fibonacci numbers, iterative

    for _ in range(n):
        print(first) # side-effect
        first, second = second, first + second # assignment

Printing first 10 Fibonacci numbers, functional expression style

    "" if n == 0 else
print(fibonacci(10), end="")

Printing a list with first 10 Fibonacci numbers, with generators

    for _ in range(n):
        yield first
        first, second = second, first + second # assignment

Printing a list with first 10 Fibonacci numbers, functional expression style

    [] if n == 0 else

Printing first 10 Fibonacci numbers, recursive style

def fibonacci(n):
    if n <= 1:
        return n

for n in range(10):


Printing first 10 Fibonacci numbers, functional expression style[1]

fibonacci_aux = \n first second->
    if n == 0 then "" else
    show first ++ "\n" ++ fibonacci_aux (n - 1) second (first + second)
fibonacci = \n-> fibonacci_aux n 0 1
main = putStr (fibonacci 10)


fibonacci_aux = \n first second->
    if n == 0 then [] else
fibonacci = \n-> fibonacci_aux n 0 1
main = putStrLn (show (fibonacci 10))

Printing the 11th Fibonacci number, functional expression style[1]

                 else if n == 1 then 1
main = putStrLn (show (fibonacci 10))


fibonacci_aux = \n first second->
    if n == 0 then first else
    fibonacci_aux (n - 1) second (first + second)
fibonacci = \n-> Fibonacci_aux n 0 1
main = putStrLn (show (fibonacci 10))


                 else select (n - 1) (tail zs)
main = putStrLn (show (fibonacci 10))


main = putStrLn (show (fibonacci 10))


fibonacci = \n-> fibonacci_aux !! n
main = putStrLn (show (fibonacci 10))


fibonacci_aux 0 first _ = first
fibonacci n = fibonacci_aux n 0 1
main = putStrLn (show (fibonacci 10))


-- an infinite list of the fibonacci numbers
-- fibs is defined in terms of fibs
fibonacci = (fibs !!)
main = putStrLn $ show $ fibonacci 11

Perl 6


# define constraints that are common to all candidates
proto fib ( UInt:D \n --> UInt:D ) {*}

multi fib ( 0 --> 0 ) { }
multi fib ( 1 --> 1 ) { }

multi fib ( \n ) {



                           # and this sequence extends lazily indefinitely







The Fibonacci function can be written in Elixir as follows:

defmodule Fibonacci do
  def fib(0), do: 0
  def fib(1), do: 1


The Fibonacci function can be written in Common Lisp as follows:

  (if (= n 0)


(defun fib (k)
     (if (or (zerop k) (= k 1))
        (+ (fib (- k 1)) (fib (- k 2)))))

The program can then be called as

(fib 10)


The Fibonacci function can be written in Clojure as follows:

(defn fib
  (loop [a 0 b 1 i n]
    (if (zero? i)

The program can then be called as

(fib 7)

Explicitly using "lazy-seq", the infinite sequence of Fibonacci numbers can be defined recursively.

;; lazy infinite sequence
(def fibs (cons 0 (cons 1 (lazy-seq (map +' fibs (rest fibs))))))

;; list of first 10 Fibonacci numbers taken from infinite sequence
(take 10 fibs)


The Fibonacci function can be written in Kotlin as follows:

fun fib(x: Int): Int = if (x == 0 || x == 1) x else fib(x - 1) + fib(x - 2)

The program can then be called as



The Fibonacci function can be written in JavaScript as follows:

var fib = (x) => (x === 0 || x === 1) ? x : fib(x - 1) + fib(x - 2);



fib(n) := n when n < 2 else

The function can then be called as




fib_Helper(prev, next, n) :=
    prev when n < 1 else
    next when n = 1 else


The Fibonacci function can be written in ruby using lambdas as follows:

  fib = lambda do |number| 
    (number == 0 || number == 1) ? number : fib.(number - 1) + fib.(number - 2) 


The Fibonacci function can be written in Tcl as a recursive function as follows:

proc fibo {x} {
    expr {$x<2? $x: [fibo [incr x -1]] + [fibo [incr x -2]]}


The Fibonacci function can be written in Scala in several ways:

Imperative "Java" style

def fibImp(n: Int): Int = {
  var i = 0
  var j = 1

  for (k <- 0 until n) {
    val l = i + j
    i = j
    j = l

Recursive style, slow

def fibRec(n: Int): Int = {
  n match {
    case 0 => 0
    case 1 => 1
    case _ => fibRec(n - 1) + fibRec(n - 2)

Recursive style with tail call optimization, fast

def fibTailRec(n: Int): Int = {
  def fib(a: Int, b: Int, c: Int): Int =
    if (a == 0) 0
    else if (a < 2) c
    else fib(a - 1, c, b + c)
  fib(n, 0, 1)

Using Scala streams

lazy val fibStream: Stream[Int] =
  0 #:: 1 #:: (fibStream zip fibStream.tail).map { n => n._1 + n._2 }

Use in industry

Functional programming has long been popular in academia, but with few industrial applications.[68]:page 11 However, recently several prominent functional programming languages have been used in commercial or industrial systems. For example, the Erlang programming language, which was developed by the Swedish company Ericsson in the late 1980s, was originally used to implement fault-tolerant telecommunications systems.[13] It has since become popular for building a range of applications at companies such as Nortel, Facebook, Électricité de France and WhatsApp.[12][14][69][70][71] The Scheme dialect of Lisp was used as the basis for several applications on early Apple Macintosh computers,[4][5] and has more recently been applied to problems such as training simulation software[6] and telescope control.[7] OCaml, which was introduced in the mid-1990s, has seen commercial use in areas such as financial analysis,[15] driver verification, industrial robot programming, and static analysis of embedded software.[16] Haskell, though initially intended as a research language,[18] has also been applied by a range of companies, in areas such as aerospace systems, hardware design, and web programming.[17][18]

Other functional programming languages that have seen use in industry include Scala,[72] F#,[19][20] (both being functional-OO hybrids with support for both purely functional and imperative programming) Wolfram Language,[10] Lisp,[73] Standard ML[74][75] and Clojure.[76]

In education

Functional programming is being used as a method to teach problem solving, algebra and geometric concepts.[77] It has also been used as a tool to teach classical mechanics in Structure and Interpretation of Classical Mechanics.

See also


  5. ^ a b Hartheimer, Anne (1987). "Programming a Text Editor in MacScheme+Toolsmith". MacTech. 3 (1). Archived from the original on 2011-06-29. Retrieved 2008-08-28. 
  8. ^ "The useR! 2006 conference schedule includes papers on the commercial use of R". R-project.org. 2006-06-08. Retrieved 2011-06-20. 
  12. ^ a b "Who uses Erlang for product development?". Frequently asked questions about Erlang. Retrieved 2018-04-27. 
  21. ^ "The 15 most popular computer languages, according to the Facebook for programmers". 2016. Retrieved 2017-07-31. 
  22. ^ "JavaScript is the World's Dominant Programming Language". 2016. Retrieved 2017-07-31. 
  23. ^ "JavaScript: The World's Most Misunderstood Programming Language". Retrieved 2017-07-31. 
  27. ^ OPtimized Applicative Language
  35. ^ The memoir of Herbert A. Simon (1991), Models of My Life pp.189-190 ISBN 0-465-04640-1 claims that he, Al Newell, and Cliff Shaw are "...commonly adjudged to be the parents of [the] artificial intelligence [field]," for writing Logic Theorist, a program that proved theorems from Principia Mathematica automatically. To accomplish this, they had to invent a language and a paradigm that, viewed retrospectively, embeds functional programming.
  40. ^ Dick Pountain. "Functional Programming Comes of Age". BYTE.com (August 1994). Archived from the original on 2006-08-27. Retrieved August 31, 2006. 
  43. ^ Hughes, John (1984). "Why Functional Programming Matters". 
  45. ^ Robert W. Harper (2009). Practical Foundations for Programming Languages (PDF). Archived from the original (PDF) on 2006-04-07. 
  46. ^ "The Compcert verified compiler". 
  49. ^ Huges, John. "Why Functional Programming Matters" (PDF). http://www.chalmers.se/cse. Chalmers Tekniska H¨ogskola.  External link in |website= (help)
  52. ^ "Lua Unofficial FAQ (uFAQ)". 
  53. ^ "Brendan Eich". 
  58. ^ "Java SE 8 Lambda Quick Start". 
  64. ^ "Which programs are fastest? | Computer Language Benchmarks Game". benchmarksgame.alioth.debian.org. Retrieved 2011-06-20. 
  66. ^ "Chapter 25. Profiling and optimization". Book.realworldhaskell.org. Retrieved 2011-06-20. 
  67. ^ [1]
  76. ^ Lorimer, R. J. "Live Production Clojure Application Announced". 
  77. ^ Emmanuel Schanzer of Bootstrap interviewed on the TV show Triangulation on the TWiT.tv network

Further reading

External links