Examine individual changes
This page allows you to examine the variables generated by the Edit Filter for an individual change.
Variables generated for this change
Variable | Value |
---|---|
Whether or not the edit is marked as minor (no longer in use) (minor_edit ) | false |
Edit count of the user (user_editcount ) | null |
Name of the user account (user_name ) | '157.49.1.171' |
Age of the user account (user_age ) | 0 |
Groups (including implicit) the user is in (user_groups ) | [
0 => '*'
] |
Global groups that the user is in (global_user_groups ) | [] |
Whether or not a user is editing through the mobile interface (user_mobile ) | true |
Page ID (page_id ) | 10933 |
Page namespace (page_namespace ) | 0 |
Page title without namespace (page_title ) | 'Functional programming' |
Full page title (page_prefixedtitle ) | 'Functional programming' |
Last ten users to contribute to the page (page_recent_contributors ) | [
0 => '86.161.75.120',
1 => '82.69.43.178',
2 => 'Greenrd',
3 => '173.95.183.16',
4 => '99.236.6.160',
5 => 'Omnipaedista',
6 => 'Fmadd',
7 => '2001:4998:EFFD:600:A84F:6F16:1EA6:3D9C',
8 => 'Jim1138',
9 => '117.244.103.222'
] |
First user to contribute to the page (page_first_contributor ) | '203.37.81.xxx' |
Action (action ) | 'edit' |
Edit summary/reason (summary ) | '' |
Old content model (old_content_model ) | 'wikitext' |
New content model (new_content_model ) | 'wikitext' |
Old page wikitext, before the edit (old_wikitext ) | '{{for|subroutine-oriented programming|Procedural programming}}
{{Programming paradigms}}
In [[computer science]], '''functional programming''' is a [[programming paradigm]]—a style of building the structure and elements of [[computer program]]s—that treats [[computation]] as the evaluation of [[function (mathematics)|mathematical function]]s and avoids changing-[[program state|state]] and [[Immutable object|mutable]] data. It is a [[declarative programming]] paradigm, which means programming is done with [[Expression (computer science)|expressions]]<ref name="expression style">{{cite web|url=https://wiki.haskell.org/Declaration_vs._expression_style#Expression_style|title=Declaration vs. expression style - HaskellWiki|publisher=}}</ref> or declarations<ref name="declaration style">{{cite web|url=https://wiki.haskell.org/Declaration_vs._expression_style#Declaration_style|title=Declaration vs. expression style - HaskellWiki|publisher=}}</ref> instead of [[statement (computer science)|statements]]. In functional code, the output value of a function depends only on the [[function argument|argument]]s that are input to the function, so calling a function ''f'' twice with the same value for an argument ''x'' will produce the same result ''f(x)'' each time. Eliminating [[side effect (computer science)|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.
Functional programming has its origins in [[lambda calculus]], a [[formal system]] developed in the 1930s to investigate [[computability]], the [[Entscheidungsproblem]], function definition, [[function application]], and [[recursion]]. Many functional [[programming language]]s can be viewed as elaborations on the lambda calculus. Another well-known declarative programming paradigm, ''[[logic programming]]'', is based on [[Relation (logic)|relations]].<ref name="hudak1989"/>
In contrast, [[imperative programming]] changes state with commands in the [[source code]], the simplest example being [[assignment (computer science)|assignment]]. Imperative programming does have functions—not in the mathematical sense—but in the sense of [[subroutine]]s. They can have [[side effect (computer science)|side effects]] that may change the value of program state. Functions without [[return value]]s therefore make sense. Because of this, they lack [[referential transparency (computer science)|referential transparency]], i.e. the same language expression can result in different values at different times depending on the state of the executing program.<ref name="hudak1989">{{cite journal | last = Hudak | first = Paul | authorlink = Paul Hudak | title = Conception, evolution, and application of functional programming languages | journal = [[Association for Computing Machinery|ACM]] Computing Surveys|volume=21|issue=3 | pages = 359–411 |date=September 1989 | url = http://www.dbnet.ece.ntua.gr/~adamo/languages/books/p359-hudak.pdf|format=PDF|doi=10.1145/72551.72554 }}</ref>
Functional programming languages have largely been emphasized in [[academic|academia]] rather than in commercial software development. However, prominent programming languages which support functional programming such as [[Common Lisp]], [[Scheme (programming language)|Scheme]],<ref name="clinger1987"/><ref name="hartheimer1987"/><ref name="kidd2007"/><ref name="cleis2006"/> [[Clojure]],<ref name="useR"/><ref name="Chambers"/> [[Wolfram Language]]<ref name="reference.wolfram.com">{{cite web | title = Wolfram Language Guide: Functional Programming | url = http://reference.wolfram.com/language/guide/FunctionalProgramming.html | year = 2015 | accessdate = 2015-08-24 }}</ref> (also known as [[Mathematica]]), [[Racket (programming language)|Racket]],<ref name="racket-video-games"/> [[Erlang (programming language)|Erlang]],<ref name="erlang-faq"/><ref name="armstrong2007"/><ref name="larson2009"/> [[OCaml]],<ref name="minksy2008"/><ref name="leroy2007"/> [[Haskell (programming language)|Haskell]],<ref name="haskell-industry"/><ref name="hudak2007"/> and [[F Sharp (programming language)|F#]]<ref name='quantFSharp'>{{cite conference | last = Mansell | first = Howard | title = Quantitative Finance in F# | url = http://cufp.galois.com/2008/abstracts.html#MansellHoward | year = 2008 | conference = CUFP 2008 | accessdate = 2009-08-29 }}</ref><ref name='businessAppsFSharp'>{{cite conference | last = Peake | first = Alex | title = The First Substantial Line of Business Application in F# | url = http://cufp.galois.com/2009/abstracts.html#AlexPeakeAdamGranicz | year = 2009 | conference = CUFP 2009 | accessdate = 2009-08-29 }}</ref> have been used in industrial and commercial applications by a wide variety of organizations. Functional programming is also supported in some [[___domain-specific programming language]]s like [[R (programming language)|R]] (statistics),<ref name="Amath-CO"/> [[J (programming language)|J]], [[K (programming language)|K]] and [[Q (programming language from Kx Systems)|Q from Kx Systems]] (financial analysis), [[XQuery]]/[[XSLT]] ([[XML]]),<ref name="Novatchev"/><ref name="Mertz"/> and Opal.<ref name="Opal (programming language)"/> Widespread ___domain-specific declarative languages like [[SQL]] and [[Lex (software)|Lex]]/[[Yacc]] use some elements of functional programming, especially in eschewing [[mutable object|mutable value]]s.<ref name="Chamberlin_Boyce"/>
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.<ref>{{cite book | last = Dominus | first = Mark J. | authorlink = Mark Jason Dominus | title = [[Higher-Order Perl]] |publisher=[[Morgan Kaufmann]] | year = 2005 |isbn = 1-55860-701-3 }}</ref> This is also true of the [[PHP]] programming language.<ref>{{cite book | last = Holywell | first = Simon | title = Functional Programming in PHP | publisher = php[architect] | year = 2014 | isbn = 9781940111056}}</ref> [[C++11]], [[Java programming|Java]] 8, and [[C Sharp (programming language)|C#]] 3.0 all added constructs to facilitate the functional style. The [[Julia (programming language)|Julia]] language also offers functional programming abilities. An interesting case is that of [[Scala (programming language)|Scala]]<ref name="effective-scala"/> – 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.
== History ==
[[Lambda calculus]] provides a theoretical framework for describing functions and their evaluation. Although it is a mathematical abstraction rather than a programming language, it forms the basis of almost all functional programming languages today. 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]].<ref>{{cite book|author1=Haskell Brooks Curry|author2=Robert Feys|title=Combinatory Logic|url=https://books.google.com/books?id=fEnuAAAAMAAJ|accessdate=10 February 2013|year=1958|publisher=North-Holland Publishing Company}}</ref>
An early functional-flavored language was [[Lisp (programming language)|Lisp]], developed in the late 1950s for the [[IBM 700/7000 series#Scientific Architecture|IBM 700/7000 series]] scientific computers by [[John McCarthy (computer scientist)|John McCarthy]] while at [[Massachusetts Institute of Technology]] (MIT).<ref>{{cite journal | first = John | last = McCarthy | authorlink = John McCarthy (computer scientist) | title = History of Lisp | journal = In [[Association for Computing Machinery|ACM]]/SIGPLAN History of Programming Languages Conference | pages = 217–223 |date=June 1978 | url = http://citeseer.ist.psu.edu/mccarthy78history.html|doi=10.1145/800025.808387 }}</ref> Lisp first introduced many paradigmatic features of functional programming, though early Lisps were [[Programming_paradigm#Multi-paradigm|multi-paradigm language]]s, and incorporated support for numerous programming styles as new paradigms evolved. Later dialects, such as [[Scheme (programming language)|Scheme]] and [[Clojure]], and offshoots such as [[Dylan (programming language)|Dylan]] and [[Julia (programming language)|Julia]], sought to simplify and rationalise Lisp around a cleanly functional core, while [[Common Lisp]] was designed to preserve and update the paradigmatic features of the numerous older dialects it replaced.<ref>{{cite journal|author1=Guy L. Steele |author2=Richard P. Gabriel |title=The Evolution of Lisp |journal= In [[Association for Computing Machinery|ACM]]/SIGPLAN Second History of Programming Languages |pages= 233-330 |date=February 1996 |url=http://dreamsongs.com/Files/HOPL2-Uncut.pdf |doi= 10.1145/234286.1057818 }}</ref>
[[Information Processing Language]] (IPL) is sometimes cited as the first computer-based functional programming language.<ref>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 which proved theorems from ''[[Principia Mathematica]]'' automatically. In order to accomplish this, they had to invent a language and a paradigm which, which viewed retrospectively, embeds functional programming.</ref> It is an [[assembly language|assembly-style language]] for manipulating lists of symbols. It does have a notion of "generator", which amounts to a function accepting a function as an argument, and, since it is an assembly-level language, code can be used as data, so IPL can be regarded as having higher-order functions. However, it relies heavily on mutating list structure and similar imperative features.
[[Kenneth E. Iverson]] developed [[APL (programming language)|APL]] in the early 1960s, described in his 1962 book ''A Programming Language'' (ISBN 9780471430148). APL was the primary influence on [[John Backus]]'s [[FP (programming language)|FP]]. In the early 1990s, Iverson and [[Roger Hui]] created [[J (programming language)|J]]. In the mid-1990s, [[Arthur Whitney (computer scientist)|Arthur Whitney]], who had previously worked with Iverson, created [[K (programming language)|K]], which is used commercially in financial industries along with its descendant [[Q (programming language from Kx Systems)|Q]].
[[John Backus]] presented [[FP (programming language)|FP]] in his 1977 [[Turing Award]] lecture "Can Programming Be Liberated From the [[Von Neumann architecture|von Neumann]] Style? A Functional Style and its Algebra of Programs".<ref>{{cite web|url=http://worrydream.com/refs/Backus-CanProgrammingBeLiberated.pdf|title=Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs|format=PDF}}</ref> He defines functional programs as being built up in a hierarchical way by means of "combining forms" that allow an "algebra of programs"; in modern language, this means that functional programs follow the [[principle of compositionality]]{{Citation needed|reason=I dont completely agree with this interpretation of John Backus definition of functional programs, which I feel is widely misunderstood. As he is very sadly no longer alive we can't ask him, but a reference for this interpretation, especially if it includes a justification, would be very beneficial.|date=February 2017}}. Backus's paper popularized research into functional programming, though it emphasized [[function-level programming]] rather than the lambda-calculus style which has come to be associated with functional programming.
In the 1970s, [[ML (programming language)|ML]] was created by [[Robin Milner]] at the [[University of Edinburgh]], and [[David Turner (computer scientist)|David Turner]] initially developed the language [[SASL (programming language)|SASL]] at the [[University of St Andrews]] and later the language [[Miranda (programming language)|Miranda]] at the [[University of Kent]]. Also in Edinburgh in the 1970s, Burstall and Darlington developed the functional language [[NPL (programming language)|NPL]].<ref>R.M. Burstall. Design considerations for a functional programming language. Invited paper, Proc. Infotech State of the Art Conf. "The Software Revolution", Copenhagen, 45–57 (1977)</ref> NPL was based on [[Kleene's recursion theorem|Kleene Recursion Equations]] and was first introduced in their work on program transformation.<ref>R.M. Burstall and J. Darlington. A transformation system for developing recursive programs. Journal of the Association for Computing Machinery 24(1):44–67 (1977)</ref> Burstall, MacQueen and Sannella then incorporated the polymorphic type checking from ML to produce the language [[Hope (programming language)|Hope]].<ref>R.M. Burstall, D.B. MacQueen and D.T. Sannella. HOPE: an experimental applicative language. Proc. 1980 LISP Conference, Stanford, 136–143 (1980).</ref> ML eventually developed into several dialects, the most common of which are now [[OCaml]] and [[Standard ML]]. Meanwhile, the development of [[Scheme (programming language)|Scheme]], a simple [[lexical scope|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.
In the 1980s, [[Per Martin-Löf]] developed [[intuitionistic type theory]] (also called ''constructive'' type theory), which associated functional programs with [[constructive proof]]s of arbitrarily complex mathematical propositions expressed as [[dependent type]]s. This led to powerful new approaches to [[interactive theorem proving]] and has influenced the development of many subsequent functional programming languages.
The [[Haskell (programming language)|Haskell language]] began with a consensus in 1987 to form an [[open standard]] for functional programming research; implementation releases have been ongoing since 1990.
== Concepts ==
A number of concepts and paradigms are specific to functional programming, and generally foreign to [[imperative programming]] (including [[object-oriented programming]]). However, programming languages are often hybrids of several programming paradigms, so programmers using "mostly imperative" languages may have utilized some of these concepts.<ref>{{cite web | url = http://byte.com/art/9408/sec11/art1.htm | archiveurl = https://web.archive.org/web/20060827094123/http://byte.com/art/9408/sec11/art1.htm | archivedate = 2006-08-27 | title = Functional Programming Comes of Age | author = Dick Pountain | work=BYTE.com (August 1994) | accessdate = August 31, 2006 }}</ref>
=== First-class and higher-order functions ===
{{main article|First-class function|Higher-order function}}
[[Higher-order function]]s are functions that can either take other functions as arguments or return them as results. In calculus, an example of a higher-order function is the [[differential operator]] <math>d/dx</math>, which returns the [[derivative]] of a function <math>f</math>.
Higher-order functions are closely related to [[first-class function]]s in that higher-order functions and first-class functions both allow functions as arguments and results of other functions. The distinction between the two is subtle: "higher-order" describes a mathematical concept of functions that operate on other functions, while "first-class" is a computer science term that describes programming language entities that have no restriction on their use (thus first-class functions can appear anywhere in the program that other first-class entities like numbers can, including as arguments to other functions and as their return values).
Higher-order functions enable [[partial application]] or [[currying]], a technique in which a function is applied to its arguments one at a time, with each application returning a new function that accepts the next argument. This allows one to succinctly express, for example, the [[successor function]] as the addition operator partially applied to the [[natural number]] one.
=== Pure functions ===
[[Pure function]]s (or expressions) have no [[side effect (computer science)|side effects]] (memory or I/O). This means that pure functions have several useful properties, many of which can be used to optimize the code:
* If the result of a pure expression is not used, it can be removed without affecting other expressions.
* 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 (computer science)|referential transparency]]), i.e. if the pure function is again called with the same arguments, the same result will be returned (this can enable caching optimizations such as [[memoization]]).
* If there is no data dependency between two pure expressions, then their order can be reversed, or they can be performed in [[parallelization|parallel]] and they cannot interfere with one another (in other terms, the evaluation of any pure expression is [[thread-safe]]).
* If the entire language does not allow side-effects, then any evaluation strategy can be used; this gives the compiler freedom to reorder or combine the evaluation of expressions in a program (for example, using [[deforestation (computer science)|deforestation]]).
While most compilers for imperative programming languages detect pure functions and perform common-subexpression elimination for pure function calls, they cannot always do this for pre-compiled libraries, which generally do not expose this information, thus preventing optimizations that involve those external functions. Some compilers, such as [[GNU Compiler Collection|gcc]], add extra keywords for a programmer to explicitly mark external functions as pure, to enable such optimizations. [[Fortran 95]] also allows functions to be designated "pure".
=== Recursion ===
{{Main article|Recursion (computer science)}}
[[Iteration]] (looping) in functional languages is usually accomplished via [[recursion]]. [[recursion (computer science)|Recursive function]]s invoke themselves, allowing an operation to be performed over and over until the [[Recursion (computer science)|base case]] is reached. 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 (programming language)|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.
Common patterns of recursion can be factored out using higher order functions, with [[catamorphism]]s and [[anamorphism]]s (or "folds" and "unfolds") being the most obvious examples. Such higher order functions play a role analogous to built-in control structures such as [[Program loops|loops]] in [[imperative languages]].
Most general purpose functional programming languages allow unrestricted recursion and are [[Turing complete]], which makes the [[halting problem]] [[undecidable problem|undecidable]], can cause unsoundness of [[equational reasoning]], and generally requires the introduction of [[inconsistency]] into the logic expressed by the language's [[type system]]. Some special purpose languages such as [[Coq]] allow only [[well-founded]] recursion and are [[strongly normalizing]] (nonterminating computations can be expressed only with infinite streams of values called [[codata (computer science)|codata]]). As a consequence, these languages fail to be Turing complete and expressing certain functions in them is impossible, but they can still express a wide class of interesting computations while avoiding the problems introduced by unrestricted recursion. Functional programming limited to well-founded recursion with a few other constraints is called [[total functional programming]].<ref name=totalfp>{{cite journal | last = Turner | first = D.A.|author-link=David Turner (computer scientist) | title = Total Functional Programming | journal = Journal of Universal Computer Science|volume=10| date = 2004-07-28 | pages = 751–768 | url = http://www.jucs.org/jucs_10_7/total_functional_programming|doi=10.3217/jucs-010-07-0751|issue=7}}</ref>
=== Strict versus non-strict evaluation ===
{{Main article|Evaluation strategy}}
Functional languages can be categorized by whether they use ''strict (eager)'' or ''non-strict (lazy)'' evaluation, concepts that refer to how function arguments are processed when an expression is being evaluated. The technical difference is in the [[denotational semantics]] of expressions containing failing or divergent computations. Under strict evaluation, the evaluation of any term containing a failing subterm will itself fail. For example, the expression:
<!-- language? -->
print length([2+1, 3*2, 1/0, 5-4])
will fail under strict evaluation because of the division by zero in the third element of the list. Under lazy evaluation, the length function will return the value 4 (i.e., the number of items in the list), since evaluating it will 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]].<ref>[http://research.microsoft.com/~simonpj/papers/slpj-book-1987/index.htm The Implementation of Functional Programming Languages]. Simon Peyton Jones, published by Prentice Hall, 1987</ref> Lazy evaluation is used by default in several pure functional languages, including [[Miranda (programming language)|Miranda]], [[Clean (programming language)|Clean]], and [[Haskell (programming language)|Haskell]].
{{Harvnb|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.<ref>{{cite web |url=http://www.cse.chalmers.se/~rjmh/Papers/whyfp.html |title=Why Functional Programming Matters |authorlink=John Hughes (computer scientist) |first=John |last=Hughes |year=1984 |ref=harv}}</ref> Launchbury 1993 <!-- a cite arguing more strongly against lazy evaluation would be preferable here, if someone knows of one. --> 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.<ref name=launchbury1993>{{cite web | url = http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.35.2016 | author = John Launchbury | title = A Natural Semantics for Lazy Evaluation | year = 1993 }}</ref> Harper 2009 proposes including both strict and lazy evaluation in the same language, using the language's type system to distinguish them.<ref>{{cite book | url = http://www.cs.cmu.edu/~rwh/plbook/book.pdf | title = Practical Foundations for Programming Languages | author = Robert W. Harper | authorlink=Robert_Harper_(computer_scientist) | year = 2009 }}</ref>
=== Type systems ===
<!-- expand this section!!! also split it into several sections -->
Especially since the development of [[Hindley–Milner type inference]] in the 1970s, functional programming languages have tended to use [[typed lambda calculus]], rejecting all invalid programs at compilation time and risking [[false positives and false negatives#False positive error|false positive errors]], as opposed to the [[untyped lambda calculus]], that accepts all valid programs at compilation time and risks [[false positives and false negatives#False negative error|false negative errors]], used in Lisp and its variants (such as [[Scheme (programming language)|Scheme]]), although they reject all invalid programs at runtime, when the information is enough to not reject valid programs. The use of [[algebraic datatypes]] makes manipulation of complex data structures convenient; the presence of strong compile-time type checking makes programs more reliable in absence of other reliability techniques like [[test-driven development]], while [[type inference]] frees the programmer from the need to manually declare types to the compiler in most cases.
Some research-oriented functional languages such as [[Coq]], [[Agda (theorem prover)|Agda]], [[Cayenne (programming language)|Cayenne]], and [[Epigram (programming language)|Epigram]] are based on [[intuitionistic type theory]], which allows types to depend on terms. Such types are called [[dependent type]]s. These type systems do not have decidable type inference and are difficult to understand and program with{{Citation needed| date = December 2011}}. But dependent types can express arbitrary propositions in [[predicate logic]]. Through the [[Curry–Howard isomorphism]], then, well-typed programs in these languages become a means of writing formal [[mathematical proof]]s from which a compiler can generate [[formal verification|certified code]]. While these languages are mainly of interest in academic research (including in [[formalized mathematics]]), they have begun to be used in engineering as well. [[Compcert]] is a [[compiler]] for a subset of the [[C (programming language)|C programming language]] that is written in Coq and formally verified.<ref>{{cite web | url = http://compcert.inria.fr/doc/index.html | title = The Compcert verified compiler }}</ref>
A limited form of dependent types called [[generalized algebraic data type]]s (GADT's) can be implemented in a way that provides some of the benefits of dependently typed programming while avoiding most of its inconvenience.<ref>{{cite web | url = http://research.microsoft.com/en-us/um/people/simonpj/papers/gadt/ | title = Simple unification-based type inference for GADTs |author1=Simon Peyton Jones |author2=Dimitrios Vytiniotis |author3=Stephanie Weirich |author4=Geoffrey Washburn | work=ICFP 2006 | pages = 50–61 }}</ref> GADT's are available in the [[Glasgow Haskell Compiler]], in [[OCaml]] (since version 4.00) and in [[Scala (programming language)|Scala]] (as "case classes"), and have been proposed as additions to other languages including Java and C#.<ref>{{cite web | title = Generalized Algebraic Data Types and Object-Oriented Programming |author1=Andrew Kennedy |author2=Claudio Russo | work=OOPSLA | date = October 2005 | ___location = San Diego, California | url = http://research.microsoft.com/~akenn/generics/gadtoop.pdf | archiveurl = https://web.archive.org/web/20061229164852/http://research.microsoft.com/~akenn/generics/gadtoop.pdf | archivedate = 2006-12-29 }} [http://lambda-the-ultimate.org/node/1134 source of citation]</ref>
=== Referential transparency ===
{{Main article|Referential transparency}}
Functional programs do not have assignment statements, that is, the value of a variable in a functional program never changes once defined. This eliminates any chances of side effects because any variable can be replaced with its actual value at any point of execution. So, functional programs are referentially transparent.<ref>{{cite web|last1=Huges|first1=John|title=Why Functional Programming Matters|url=http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf|website=http://www.chalmers.se/cse|publisher=Chalmers Tekniska H¨ogskola}}</ref>
Consider [[C (programming language)|C]] assignment statement <code>x = x * 10</code>, this changes the value assigned to the variable <code>x</code>. Let us say that the initial value of <code>x</code> was <code>1</code>, then two consecutive evaluations of the variable <code>x</code> will yield <code>10</code> and <code>100</code> respectively. Clearly, replacing <code>x = x * 10</code> with either <code>10</code> or <code>100</code> gives a program with different meaning, and so the expression ''is not'' referentially transparent. In fact, assignment statements are never referentially transparent.
Now, consider another function such as <code>int plusone(int x) {return x+1;}</code> ''is'' transparent, as it will not implicitly change the input x and thus has no such [[side effect (computer science)|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.<ref>{{cite journal | last = Hartel | first = Pieter |author2=Henk Muller |author3=Hugh Glaser | title = The Functional C experience | journal = Journal of Functional Programming | volume=14 |issue=2 | pages = 129–135 |date=March 2004 | url = http://www.ub.utwente.nl/webdocs/ctit/1/00000084.pdf |format=PDF| doi=10.1017/S0956796803004817}}; {{cite web | title = Functional programming in Python, Part 3 | url = http://www-128.ibm.com/developerworks/linux/library/l-prog3.html | archiveurl = http://wayback.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog3.html | archivedate = 2007-10-16 | author = David Mertz | accessdate = 2006-09-17 | work=IBM developerWorks}}([http://wayback.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog.html Part 1], [http://wayback.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog2.html Part 2])</ref> For example, both [[D (programming language)|D]] and [[Fortran 95]] explicitly support pure functions.<ref>{{cite web | url = http://www.digitalmars.com/d/2.0/function.html#pure-functions | title = Functions — D Programming Language 2.0 |publisher=Digital Mars | accessdate = 2011-06-20 }}</ref>
[[JavaScript]], [[Lua (programming language)|Lua]]<ref>{{cite web|url=http://www.luafaq.org/#T1.2|title=Lua Unofficial FAQ (uFAQ)|publisher=}}</ref> and [[Python (programming language)|Python]] had [[First-class function|first class functions]] from their inception.<ref>{{cite web|url=https://brendaneich.com/2008/04/popularity/|title=Brendan Eich|publisher=}}</ref> Amrit Prem added support to Python for "[[anonymous function|lambda]]", "[[Map (higher-order function)|map]]", "[[Fold (higher-order function)|reduce]]", and "[[Filter (higher-order function)|filter]]" in 1994, as well as closures in Python 2.2,<ref>{{cite web |url=http://python-history.blogspot.de/2009/04/origins-of-pythons-functional-features.html |title=Origins of Python's "Functional" Features |last=van Rossum |first=Guido |authorlink=Guido van Rossum |publisher=[http://python-history.blogspot.de/ The History of Python] |date=2009-04-21 |accessdate=2012-09-27 }}</ref> though Python 3 relegated "reduce" to the <code>functools</code> standard library module.<ref>{{cite web | url = https://docs.python.org/dev/library/functools.html#functools.reduce | title = functools — Higher order functions and operations on callable objects | publisher=Python Software Foundation | date = 2011-07-31 | accessdate = 2011-07-31}}</ref> First-class functions have been introduced into other mainstream languages such as [[PHP]] 5.3, [[Visual Basic]] 9, [[C Sharp (programming language)|C#]] 3.0, and [[C++11]].{{citation needed|date=April 2015}}
In [[Java (programming language)|Java]], [[anonymous class]]es can sometimes be used to simulate [[Closure (computer science)|closure]]s;<ref>{{cite book | last = Skarsaune | first = Martin | title = The SICS Java Port Project Automatic Translation of a Large Object Oriented System from Smalltalk to Java | year = 2008 }}</ref> however, anonymous classes are not always proper replacements to [[Closure (computer science)|closure]]s because they have more limited capabilities.<ref>{{cite web|last=Gosling|first=James|title=Closures|url=http://blogs.oracle.com/jag/entry/closures|work=James Gosling: on the Java Road|publisher=Oracle|accessdate=11 May 2013}}</ref> Java 8 supports lambda expressions as a replacement for some anonymous classes.<ref>{{cite web|url=https://blogs.oracle.com/javatraining/entry/java_se_8_lambda_quick|title=Java SE 8 Lambda Quick Start}}</ref> 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|date=March 2014}}
In [[C Sharp (programming language)|C#]], [[anonymous class]]es are not necessary, because [[Closure (computer science)|closure]]s and lambdas are fully supported. Libraries and language extensions for immutable data structures are being developed to aid programming in the functional style in C#.
Many [[object-oriented]] [[Design pattern (computer science)|design pattern]]s are expressible in functional programming terms: for example, the [[strategy pattern]] simply dictates use of a higher-order function, and the [[visitor (design pattern)|visitor]] pattern roughly corresponds to a [[catamorphism]], or [[fold (higher-order function)|fold]].
Similarly, the idea of immutable data from functional programming is often included in imperative programming languages,<ref>{{cite book | title = Effective Java | edition = Second | first = Joshua | last = Bloch | pages = Item 15 }}</ref> for example the tuple in Python, which is an immutable array.
===Data structures===
{{main article|Purely functional data structure}}
Purely functional [[data structure]]s are often represented in a different way than their [[imperative programming|imperative]] counterparts.<ref>[http://www.cambridge.org/us/academic/subjects/computer-science/algorithmics-complexity-computer-algebra-and-computational-g/purely-functional-data-structures ''Purely functional data structures''] by [[Chris Okasaki]], [[Cambridge University Press]], 1998, ISBN 0-521-66350-4</ref> For example, [[array data structure|array]] with constant-time access and update is a basic component of most imperative languages and many imperative data-structure, such as [[hash table]] and [[binary heap]], are based on arrays. Arrays can be replaced by [[Map (computer science)|map]] or [[random access list]], which admits purely functional implementation, but the access and update time is [[logarithm]]ic. Therefore, purely functional data structures can be used in languages which are non-functional, but they may not be the most efficient tool available, especially if persistency is not required.
== Comparison to imperative programming ==
Functional programming is very different from [[imperative programming]]. The most significant differences stem from the fact that functional programming avoids [[side effect (computer science)|side effects]], which are used in imperative programming to implement state and I/O. Pure functional programming completely prevents side-effects and provides [[referential transparency (computer science)|referential transparency]].
Higher-order functions are rarely used in older imperative programming. A traditional imperative program might use a loop to traverse and modify a list. A functional program, on the other hand, would probably use a higher-order “map” function that takes a function and a list, generating and returning a new list by applying the function to each list item.
=== Simulating state ===
There are tasks (for example, maintaining a bank account balance) that often seem most naturally implemented with state. Pure functional programming performs these tasks, and I/O tasks such as accepting user input and printing to the screen, in a different way.
The pure functional programming language [[Haskell (programming language)|Haskell]] implements them using [[monad (functional programming)|monads]], derived from [[category theory]]. Monads offer a way to abstract certain types of computational patterns, including (but not limited to) modeling of computations with mutable state (and other side effects such as I/O) in an imperative manner without losing purity. While existing monads may be easy to apply in a program, given appropriate templates and examples, many students find them difficult to understand conceptually, e.g., when asked to define new monads (which is sometimes needed for certain types of libraries).<ref>{{cite web | last = Newbern | first = J. | title = All About Monads: A comprehensive guide to the theory and practice of monadic programming in Haskell | url = http://monads.haskell.cz/html/index.html/html/ | accessdate = 2008-02-14 }}</ref>
Another way in which functional languages can simulate state is by passing around a [[data structure]] that represents the current state as a parameter to function calls. On each function call, a copy of this data structure is created with whatever differences are the result of the function. This is referred to as '[[state-passing style]]'.
<!-- TO DO: Expand -->
Impure functional languages usually include a more direct method of managing mutable state. [[Clojure]], for example, uses managed references that can be updated by applying pure functions to the current state. This kind of approach enables mutability while still promoting the use of pure functions as the preferred way to express computations.
<!-- TO DO: Expand / example code?? -->
Alternative methods such as [[Hoare logic]] and [[uniqueness type|uniqueness]] have been developed to track side effects in programs. Some modern research languages use [[effect system]]s to make the presence of side effects explicit.
<!-- TO DO: Expand -->
=== Efficiency issues ===
Functional programming languages are typically less efficient in their use of [[central processing unit|CPU]] and memory than imperative languages such as [[C (programming language)|C]] and [[Pascal (programming language)|Pascal]].<ref>{{cite book|author=Larry C. Paulson|title=ML for the Working Programmer|url=https://books.google.com/books?id=XppZdaDs7e0C|accessdate=10 February 2013|date=28 June 1996|publisher=Cambridge University Press|isbn=978-0-521-56543-1}}</ref> <!-- Paulson mentions the reputation for inefficiency in Sec. 1.5; perhaps a more in-depth discussion could be found. --> 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. <!-- perhaps this could be formulated by someone who knows the subject, I was simply curious about unexplained statement "logarithmic slowdown" --> 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).<ref name="Spiewak"/> However, such slowdowns are not universal. For programs that perform intensive numerical computations, functional languages such as [[OCaml]] and [[Clean (programming language)|Clean]] are only slightly slower than C.<ref>{{cite web | url = http://benchmarksgame.alioth.debian.org/u32/which-programs-are-fastest.php?gcc=on&ghc=on&clean=on&ocaml=on&sbcl=on&fsharp=on&racket=on&clojure=on&hipe=on&calc=chart | title = Which programs are fastest? | Computer Language Benchmarks Game | publisher=benchmarksgame.alioth.debian.org | accessdate = 2011-06-20 }}</ref> For programs that handle large [[matrix (mathematics)|matrices]] and multidimensional [[database]]s, [[array programming|array]] functional languages (such as [[J (programming language)|J]] and [[K (programming language)|K]]) were designed with speed optimizations.
Immutability of data can in many cases lead to execution efficiency by allowing the compiler to make assumptions that are unsafe in an imperative language, thus increasing opportunities for [[inline expansion]].<ref>{{cite journal | title = Immutability specification and its applications |author1=Igor Pechtchanski |author2=Vivek Sarkar | journal = Concurrency and Computation: Practice and Experience | volume = 17 | issue = 5–6 | pages = 639–662 | year = 2005 | doi = 10.1002/cpe.853 }}</ref>
[[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 leak]]s if used improperly). Launchbury 1993<ref name=launchbury1993/> discusses theoretical issues related to memory leaks from lazy evaluation, and O'Sullivan ''et al.'' 2008<ref>{{cite web | url = http://book.realworldhaskell.org/read/profiling-and-optimization.html#x_eK1 | title = Chapter 25. Profiling and optimization |publisher=Book.realworldhaskell.org | accessdate = 2011-06-20 }}</ref> 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|date=June 2014}}.
=== Coding styles ===
{{unreferenced section|date=July 2013}}
Imperative programs have the environment and a sequence of steps manipulating the environment. Functional programs have an expression that is successively substituted until it reaches normal form. An example illustrates this with different solutions to the same programming goal (calculating [[Fibonacci number]]s).
====[[Python (programming language)|Python]]====
Printing first 10 Fibonacci numbers, iterative
<source lang="python">
def fibonacci(n, first=0, second=1):
while n != 0:
print(first, end="\n") # side-effect
n, first, second = n - 1, second, first + second # assignment
fibonacci(10)
</source>
Printing first 10 Fibonacci numbers, functional expression style
<source lang="python">
fibonacci = (lambda n, first=0, second=1:
"" if n == 0 else
str(first) + "\n" + fibonacci(n - 1, second, first + second))
print(fibonacci(10), end="")
</source>
Printing a list with first 10 Fibonacci numbers, with generators
<source lang="python">
def fibonacci(n, first=0, second=1):
while n != 0:
yield first
n, first, second = n - 1, second, first + second # assignment
print(list(fibonacci(10)))
</source>
Printing a list with first 10 Fibonacci numbers, functional expression style
<source lang="python">
fibonacci = (lambda n, first=0, second=1:
[] if n == 0 else
[first] + fibonacci(n - 1, second, first + second))
print(fibonacci(10))
</source>
====[[Haskell (programming language)|Haskell]]====
Printing first 10 Fibonacci numbers, functional expression style<ref name="expression style" />
<source lang="haskell">
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)
</source>
Printing a list with first 10 Fibonacci numbers, functional expression style<ref name="expression style" />
<source lang="haskell">
fibonacci_aux = \n first second->
if n == 0 then [] else
[first] ++ fibonacci_aux (n - 1) second (first + second)
fibonacci = \n-> fibonacci_aux n 0 1
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" />
<source lang="haskell">
fibonacci = \n-> if n == 0 then 0
else if n == 1 then 1
else fibonacci(n - 1) + fibonacci(n - 2)
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style,<ref name="expression style" /> [[tail recursive]]
<source lang="haskell">
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))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" /> with recursive lists
<source lang="haskell">
fibonacci_aux = \first second-> first : fibonacci_aux second (first + second)
select = \n zs-> if n==0 then head zs
else select (n - 1) (tail zs)
fibonacci = \n-> select n (fibonacci_aux 0 1)
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" /> with primitives for recursive lists
<source lang="haskell">
fibonacci_aux = \first second-> first : fibonacci_aux second (first + second)
fibonacci = \n-> (fibonacci_aux 0 1) !! n
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" /> with primitives for recursive lists, more concisely
<source lang="haskell">
fibonacci_aux = 0:1:zipWith (+) fibonacci_aux (tail fibonacci_aux)
fibonacci = \n-> fibonacci_aux !! n
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional declaration style,<ref name="declaration style" /> [[tail recursive]]
<source lang="haskell">
fibonacci_aux 0 first _ = first
fibonacci_aux n first second = fibonacci_aux (n - 1) second (first + second)
fibonacci n = fibonacci_aux n 0 1
main = putStrLn (show (fibonacci 10))
</source>Printing the 11th Fibonacci number, functional declaration style, using [[Lazy evaluation|lazy]] [[Lazy evaluation|infinite lists]] and primitives<syntaxhighlight lang="haskell">
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
-- an infinite list of the fibonacci numbers
-- fibs is defined in terms of fibs
fibonacci = (fibs !!)
main = putStrLn $ show $ fibonacci 11
</syntaxhighlight>
====Perl 6====
As influenced by Haskell and others, [[Perl 6]] has several functional and declarative approaches to problems. For example, you can declaratively build up a well-typed recursive version (the type constraints are optional) through signature pattern matching:
<source lang="perl6">
subset NonNegativeInt of Int where * >= 0;
proto fib (|) is cached returns NonNegativeInt {*}
multi fib (0) { 0 }
multi fib (1) { 1 }
multi fib (NonNegativeInt $n) { fib($n - 1) + fib($n - 2) }
for ^10 -> $n { say fib($n) }
</source>
An alternative to this is to construct a lazy iterative sequence, which appears as an almost direct illustration of the sequence:
<source lang="perl6">
my @fib = 0, 1, *+* ... *; # Each additional entry is the sum of the previous two
# and this sequence extends lazily indefinitely
say @fib[^10]; # Display the first 10 entries
</source>
====[[Erlang (programming language)|Erlang]]====
'''[[Erlang (programming language)|Erlang]]''' is a functional, concurrent, general-purpose programming language. A [[Fibonacci number|Fibonacci]] algorithm implemented in Erlang (Note: This is only for demonstrating the Erlang [[Syntax (programming languages)|syntax]]. Use other algorithms for fast performance<ref>[http://www.aquabu.com/2008/02/16/fibonacci-sequence-recursion-in-erlang/]{{dead link|date=February 2016}}</ref>):
<source lang="erlang">
-module(fib). % This is the file 'fib.erl', the module and the filename must match
-export([fib/1]). % This exports the function 'fib' of arity 1
fib(1) -> 1; % If 1, then return 1, otherwise (note the semicolon ; meaning 'else')
fib(2) -> 1; % If 2, then return 1, otherwise
fib(N) -> fib(N - 2) + fib(N - 1).
</source>
==== Elixir ====
'''[[Elixir (programming language)|Elixir]]''' is a functional, concurrent, general-purpose programming language that runs on the [[Erlang (programming language)|Erlang virtual machine (BEAM)]].
The Fibonacci function can be written in Elixir as follows:<syntaxhighlight lang="elixir">
defmodule Fibonacci do
def fib(0), do: 0
def fib(1), do: 1
def fib(n), do: fib(n-1) + fib(n-2)
end
</syntaxhighlight>
====Lisp====
The Fibonacci function can be written in [[Common Lisp]] as follows:
<source lang="lisp">
(defun fib (n &optional (a 0) (b 1))
(if (= n 0)
a
(fib (- n 1) b (+ a b))))
</source>
The program can then be called as
<source lang="lisp">
(fib 10)
</source>
====[[Clojure]]====
The Fibonacci function can be written in [[Clojure]] as follows:
<source lang="clojure">
(defn fib
[n]
(loop [a 0 b 1 i n]
(if (zero? i)
a
(recur b (+ a b) (dec i)))))
</source>
The program can then be called as
<source lang="clojure">
(fib 7)
</source>
====D====
[[D (programming language)|D]] has support for functional programming{{clarify|date=April 2015}}{{citation needed|date=April 2015}}:
<source lang="d">
import std.stdio;
import std.range;
void main()
{
/* 'f' is a range representing the first 10 Fibonacci numbers */
auto f = recurrence!((seq, i) => seq[0] + seq[1])(0, 1)
.take(10);
writeln(f);
}
</source>
====R====
[[R (programming language)|R]] is an environment for statistical computing and graphics. It is also a functional programming language.
The Fibonacci function can be written in [[R (programming language)|R]] as a recursive function as follows:
<source lang="rsplus">
fib <- function(n) {
if (n <= 2) 1
else fib(n - 1) + fib(n - 2)
}
</source>
Or it can be written as a singly recursive function:
<source lang="rsplus">
fib <- function(n,a=1,b=1) {
if (n == 1) a
else fib(n-1,b,a+b)
}
</source>
Or it can be written as an iterative function:
<source lang="rsplus">
fib <- function(n) {
if (n == 1) 1
else if (n == 2) 1
else {
fib<-c(1,1)
for (i in 3:n) fib<-c(0,fib[1])+fib[2]
fib[2]
}
}
</source>
The function can then be called as
<source lang="rsplus">
fib(10)
</source>
====[[SequenceL]]====
SequenceL is a functional, concurrent, general-purpose programming language. The Fibonacci function can be written in SequenceL as follows:
<source lang="haskell">
fib(n) := n when n < 2 else
fib(n - 1) + fib(n - 2);
</source>
The function can then be called as
<source lang="haskell">
fib(10)
</source>
To reduce the memory consumed by the call stack when computing a large Fibonacci term, a tail-recursive version can be used. A tail-recursive function is implemented by the SequenceL compiler as a memory-efficient looping structure:
<source lang="haskell">
fib(n) := fib_Helper(0, 1, n);
fib_Helper(prev, next, n) :=
prev when n < 1 else
next when n = 1 else
fib_Helper(next, next + prev, n - 1);
</source>
== Use in industry ==
Functional programming has long been popular in academia, but with few industrial applications.<ref name='programmingScala'>{{cite book | first1 = Martin | last1 = Odersky | first2 = Lex | last2 = Spoon | first3 = Bill | last3 = Venners | date = December 13, 2010 | title = Programming in Scala: A Comprehensive Step-by-step Guide | publisher = [[Artima Inc]] | edition = 2nd | pages = 883/852 | isbn = 978-0-9815316-4-9 | url = http://www.artima.com/shop/programming_in_scala_2ed }}</ref>{{rp|page 11}} However, recently several prominent functional programming languages have been used in commercial or industrial systems. For example, the [[Erlang (programming language)|Erlang]] programming language, which was developed by the [[Sweden|Swedish]] company [[Ericsson]] in the late 1980s, was originally used to implement fault-tolerant telecommunications systems.<ref name="armstrong2007"/> It has since become popular for building a range of applications at companies such as [[T-Mobile]], [[Nortel]], [[Facebook]], [[Électricité de France]] and [[WhatsApp]].<ref name="erlang-faq"/><ref name="larson2009"/><ref>{{cite conference | last = Piro | first = Christopher | title = Functional Programming at Facebook | url = http://cufp.galois.com/2009/abstracts.html#ChristopherPiroEugeneLetuchy | year = 2009 | conference = CUFP 2009 | accessdate = 2009-08-29 }}</ref><ref name="Sim-Diasca"/><ref name="whatsapp.blog.2012">[http://blog.whatsapp.com/index.php/2012/01/1-million-is-so-2011/ 1 million is so 2011] // WhatsApp blog, 2012-01-06: "the last important piece of our infrastracture is Erlang"</ref> The [[Scheme (programming language)|Scheme]] dialect of [[Lisp (programming language)|Lisp]] was used as the basis for several applications on early [[Apple Macintosh]] computers,<ref name="clinger1987"/><ref name="hartheimer1987"/> and has more recently been applied to problems such as training [[Computer simulation|simulation software]]<ref name="kidd2007"/> and [[telescope]] control.<ref name="cleis2006"/> [[OCaml]], which was introduced in the mid-1990s, has seen commercial use in areas such as financial analysis,<ref name="minksy2008"/> [[software driver|driver]] verification, industrial [[robot]] programming, and static analysis of [[embedded software]].<ref name="leroy2007"/> [[Haskell (programming language)|Haskell]], although initially intended as a research language,<ref name="hudak2007"/> has also been applied by a range of companies, in areas such as aerospace systems, hardware design, and web programming.<ref name="haskell-industry"/><ref name="hudak2007"/>
Other functional programming languages that have seen use in industry include [[Scala (programming language)|Scala]],<ref>{{cite conference | last = Momtahan | first = Lee | title = Scala at EDF Trading: Implementing a Domain-Specific Language for Derivative Pricing with Scala | url = http://cufp.galois.com/2009/abstracts.html#LeeMomtahan | year = 2009 | conference = CUFP 2009 | accessdate = 2009-08-29 }}</ref> [[F Sharp (programming language)|F#]],<ref name='quantFSharp'/><ref name='businessAppsFSharp'/> (both being functional-OO hybrids with support for both purely functional and imperative programming) [[Wolfram Language]],<ref name="reference.wolfram.com"/> [[Lisp (programming language)|Lisp]],<ref>{{cite web | last = Graham | first = Paul | title = Beating the Averages | url = http://www.paulgraham.com/avg.html | year = 2003 | accessdate = 2009-08-29 }}</ref> [[Standard ML]]<ref>{{cite conference | last = Sims | first = Steve | title = Building a Startup with Standard ML | url = http://cufp.galois.com/2006/slides/SteveSims.pdf | year = 2006 | conference = CUFP 2006 | accessdate = 2009-08-29 }}</ref><ref>{{cite conference | last = Laurikari | first = Ville | title = Functional Programming in Communications Security. | url = http://cufp.galois.com/2007/abstracts.html#VilleLaurikari | year = 2007 | conference = CUFP 2007 | accessdate = 2009-08-29 }}</ref> and [[Clojure]].<ref>{{cite web | url = http://www.infoq.com/news/2009/01/clojure_production | last = Lorimer | first = R. J. | title = Live Production Clojure Application Announced }}</ref>
==In education==
Functional programming is being used as a method to teach problem solving, algebra and geometric concepts.<ref name="bootstrapworld">{{Triangulation|196|Emmanuel Schanzer of Bootstrap}}</ref>
It has also been used as a tool to teach classical mechanics in [[Structure and Interpretation of Classical Mechanics]].
== See also ==
{{Portal|Computer programming}}
* [[Purely functional programming]]
* [[Comparison of programming paradigms]]
* [[Eager evaluation]]
* [[List of functional programming topics]]
* [[Nested function]]
* [[Inductive functional programming]]
* [[Functional reactive programming]]
== References ==
{{reflist|colwidth=30em|refs=
<ref name="clinger1987">{{cite journal | last = Clinger | first = Will | title = MultiTasking and MacScheme | magazine = MacTech | volume = 3 | issue = 12 | year = 1987 | url = http://www.mactech.com/articles/mactech/Vol.03/03.12/Multitasking/index.html | accessdate = 2008-08-28 }}</ref>
<ref name="hartheimer1987">{{cite journal | last = Hartheimer | first = Anne | title = Programming a Text Editor in MacScheme+Toolsmith | magazine = MacTech | volume = 3 | issue = 1 | year = 1987 | url = http://www.mactech.com/articles/mactech/Vol.03/03.1/SchemeWindows/index.html | accessdate = 2008-08-28 }}</ref>
<ref name="kidd2007">{{cite conference | last = Kidd | first = Eric | url = http://cufp.galois.com/2007/abstracts.html#EricKidd | title = Terrorism Response Training in Scheme | conference = CUFP 2007 | accessdate = 2009-08-26 }}</ref>
<ref name="cleis2006">{{cite conference | last = Cleis | first = Richard | url = http://cufp.galois.com/2006/abstracts.html#RichardCleis | title = Scheme in Space | conference = CUFP 2006 | accessdate = 2009-08-26 }}</ref>
<ref name="erlang-faq">{{cite web | title = Who uses Erlang for product development? | work=Frequently asked questions about Erlang | url = http://www.erlang.org/faq/faq.html#AEN50 | accessdate = 2007-08-05 }}</ref>
<ref name="armstrong2007">{{cite conference | last = Armstrong | first = Joe | title = A history of Erlang | conference = Third ACM SIGPLAN Conference on History of Programming Languages | ___location = San Diego, California | date = June 2007 | url = http://doi.acm.org/10.1145/1238844.1238850 | accessdate = 2009-08-29 }}</ref>
<ref name="larson2009">{{cite journal | last = Larson | first = Jim | title = Erlang for concurrent programming | journal = Communications of the ACM | volume= 52 | issue= 3 | date = March 2009 | doi=10.1145/1467247.1467263 | page=48 }}</ref>
<ref name="minksy2008">{{cite journal | last = Minsky | first = Yaron | last2 = Weeks | first2 = Stephen | title = Caml Trading — experiences with functional programming on Wall Street | journal = Journal of Functional Programming | volume = 18 | issue = 4 | pages = 553–564 | publisher = Cambridge University Press | ___location = |date=July 2008 | url = http://journals.cambridge.org/action/displayAbstract?aid=1899164 | doi = 10.1017/S095679680800676X | accessdate = 2008-08-27 }}</ref>
<ref name="leroy2007">{{cite conference | last = Leroy | first = Xavier | title = Some uses of Caml in Industry | url = http://cufp.galois.com/2007/slides/XavierLeroy.pdf | conference = CUFP 2007 | accessdate = 2009-08-26 }}</ref><ref name="haskell-industry">{{cite web | title = Haskell in industry | work = Haskell Wiki | url = http://www.haskell.org/haskellwiki/Haskell_in_industry | accessdate = 2009-08-26 | quote=Haskell has a diverse range of use commercially, from aerospace and defense, to finance, to web startups, hardware design firms and lawnmower manufacturers. }}</ref>
<ref name="effective-scala">{{cite web | title = Effective Scala | work = Scala Wiki | url = http://twitter.github.com/effectivescala/?sd | accessdate = 2012-02-21 | quote=Effective Scala. }}</ref><ref name="racket-video-games">{{cite web | title = State-Based Scripting in Uncharted 2 | url = http://www.gameenginebook.com/gdc09-statescripting-uncharted2.pdf | archiveurl = https://web.archive.org/web/20121215014637/http://www.gameenginebook.com/gdc09-statescripting-uncharted2.pdf | archivedate = 2012-12-15 | accessdate = 2011-08-08 }}</ref>
<ref name="hudak2007">{{cite conference | last = Hudak | first = Paul |author2=Hughes, J. |author3=Jones, S. P. |author4=Wadler, P. | authorlink=Paul Hudak | title = A history of Haskell: being lazy with class | url=http://dl.acm.org/citation.cfm?doid=1238844.1238856 | conference = Third ACM SIGPLAN Conference on History of Programming Languages | ___location = San Diego, California| date = June 2007 | doi = 10.1145/1238844.1238856 | accessdate = 2013-09-26 }}</ref>
<ref name="useR">{{cite web | url = http://www.r-project.org/useR-2006/program.html | title = The useR! 2006 conference schedule includes papers on the commercial use of R |publisher=R-project.org | date = 2006-06-08 | accessdate = 2011-06-20 }}</ref><ref name="Chambers">{{cite book | last = Chambers | first = John M. | authorlink=John Chambers (programmer) | title = Programming with Data: A Guide to the S Language | publisher=Springer Verlag | year = 1998 | pages = 67–70 | isbn = 978-0-387-98503-9 }}</ref><ref name="Amath-CO">{{cite web | author = Department of Applied Math, University of Colorado | title = Functional vs. Procedural Programming Language | url = http://amath.colorado.edu/computing/mmm/funcproc.html | archiveurl = https://web.archive.org/web/20071113175801/http://amath.colorado.edu/computing/mmm/funcproc.html | archivedate = 2007-11-13 | accessdate = 2006-08-28 }}</ref>
<ref name="Novatchev">{{cite web | url = http://www.topxml.com/xsl/articles/fp/ | author = Dimitre Novatchev | title = The Functional Programming Language XSLT — A proof through examples | accessdate = May 27, 2006 | work=TopXML }}</ref><ref name="Mertz">{{cite web | url = http://gnosis.cx/publish/programming/xml_models_fp.html | author = David Mertz | title = XML Programming Paradigms (part four): Functional Programming approached to XML processing | accessdate = May 27, 2006 | work=IBM developerWorks }}</ref>
<ref name="Chamberlin_Boyce">{{cite journal | title = SEQUEL: A structured English query language | author = [[Donald D. Chamberlin]] and [[Raymond F. Boyce]] | journal = Proceedings of the 1974 ACM SIGFIDET | pages = 249–264 | year = 1974 }}</ref><ref name="Sim-Diasca">{{cite web | title = Sim-Diasca: a large-scale discrete event concurrent simulation engine in Erlang | url = http://research.edf.com/research-and-the-scientific-community/software/sim-diasca-80704.html |date=November 2011 }}</ref>
<ref name="Spiewak">{{cite web | url = http://www.codecommit.com/blog/scala/implementing-persistent-vectors-in-scala | author = Daniel Spiewak | title = Implementing Persistent Vectors in Scala | accessdate = Apr 17, 2012}}</ref>
<ref name="Opal (programming language)">[[Opal (programming language)|OPtimized Applicative Language]]</ref>
}}
== Further reading ==
* {{cite book|last1=Abelson|first1=Hal|authorlink1=Hal Abelson|last2=Sussman|first2=Gerald Jay|authorlink2=Gerald Jay Sussman | title = Structure and Interpretation of Computer Programs | url = http://mitpress.mit.edu/sicp/ | year = 1985|publisher=MIT Press}}
* Cousineau, Guy and Michel Mauny. ''The Functional Approach to Programming''. Cambridge, UK: [[Cambridge University Press]], 1998.
* Curry, Haskell Brooks and Feys, Robert and Craig, William. ''Combinatory Logic''. Volume I. North-Holland Publishing Company, Amsterdam, 1958.
* {{cite book | last1 = Curry | first1 = Haskell B. | first2 = J. Roger | last2 = Hindley | first3 = Jonathan P. | last3 = Seldin | authorlink1 = Haskell Curry | authorlink2 = J. Roger Hindley | authorlink3 = Jonathan P. Seldin | title = Combinatory Logic | volume = Vol. II | year = 1972 | publisher = North Holland | ___location = Amsterdam | isbn = 0-7204-2208-6 }}
* Dominus, Mark Jason. ''[http://hop.perl.plover.com/book/pdf/HigherOrderPerl.pdf Higher-Order Perl]''. [[Morgan Kaufmann]]. 2005.
* {{cite book|last1=Felleisen|first1=Matthias|last2=Findler|first2=Robert|last3=Flatt|first3=Matthew|first4=Shriram |last4=Krishnamurthi | title = How to Design Programs | url = http://www.htdp.org | year = 2001|publisher=MIT Press}}
* Graham, Paul. ''ANSI Common LISP''. Englewood Cliffs, New Jersey: [[Prentice Hall]], 1996.
* MacLennan, Bruce J. ''Functional Programming: Practice and Theory''. Addison-Wesley, 1990.
* {{cite book|last1=O'Sullivan|first1=Brian|last2=Stewart|first2=Don|last3=Goerzen|first3=John | title = Real World Haskell | url = http://book.realworldhaskell.org/read/ | year = 2008|publisher=O'Reilly}}
* Pratt, Terrence, W. and Marvin V. Zelkowitz. ''Programming Languages: Design and Implementation''. 3rd ed. Englewood Cliffs, New Jersey: [[Prentice Hall]], 1996.
* Salus, Peter H. ''Functional and Logic Programming Languages''. Vol. 4 of Handbook of Programming Languages. Indianapolis, Indiana: [[Macmillan Technical Publishing]], 1998.
* Thompson, Simon. ''Haskell: The Craft of Functional Programming''. Harlow, England: [[Addison-Wesley Longman Limited]], 1996.
== External links ==
{{Spoken Wikipedia|En-Functional_programming.ogg|2011-08-25}}
*{{cite web
| last = Ford
| first = Neal
| title = Functional thinking: Why functional programming is on the rise
| accessdate = 2013-02-24
| date = 2012-01-29
| url = http://www.ibm.com/developerworks/java/library/j-ft20/index.html
}}
* {{cite web
| last = Akhmechet
| first = Slava
| title = defmacro – Functional Programming For The Rest of Us
| accessdate = 2013-02-24
| date = 2006-06-19
| url = http://www.defmacro.org/ramblings/fp.html
}} An introduction
* ''Functional programming in Python'' (by David Mertz): [http://gnosis.cx/publish/programming/charming_python_13.html part 1], [http://gnosis.cx/publish/programming/charming_python_16.html part 2], [http://gnosis.cx/publish/programming/charming_python_19.html part 3]
{{Programming language}}
{{Authority control}}
{{DEFAULTSORT:Functional programming}}
[[Category:Programming paradigms]]
[[Category:Functional programming| ]]' |
New page wikitext, after the edit (new_wikitext ) | '{{for|subroutine-oriented programming|Procedural programming}}
{{Programming paradigms}}
In [[computer science]], '''functional programming''' is a [[programming paradigm]]—a style of building the structure and elements of [[computer program]]s—that treats [[computation]] as the evaluation of [[function (mathematics)|mathematical function]]s and avoids changing-[[program state|state]] and [[Immutable object|mutable]] data. It is a [[declarative programming]] paradigm, which means programming is done with [[Expression (computer science)|expressions]]<ref name="expression style">{{cite web|url=https://wiki.haskell.org/Declaration_vs._expression_style#Expression_style|title=Declaration vs. expression style - HaskellWiki|publisher=}}</ref> or declarations<ref name="declaration style">{{cite web|url=https://wiki.haskell.org/Declaration_vs._expression_style#Declaration_style|title=Declaration vs. expression style - HaskellWiki|publisher=}}</ref> instead of [[statement (computer science)|statements]]. In functional code, the output value of a function depends only on the [[function argument|argument]]s that are input to the function, so calling a function ''f'' twice with the same value for an argument ''x'' will produce the same result ''f(x)'' each time. Eliminating [[side effect (computer science)|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.
Functional programming has its origins in [[lambda calculus]], a [[formal system]] developed in the 1930s to investigate [[computability]], the [[Entscheidungsproblem]], function definition, [[function applkmllllllllllllllll
ication]], and [[recursion]]. Many functional [[programming language]]s can be viewed as elaborations on the lambda calculus. Another well-known declarative programming paradigm, ''[[logic programming]]'', is based on [[Relation (logic)|relations]].<ref name="hudak1989"/>
In contrast, [[imperative programming]] changes state with commands in the [[source code]], the simplest example being [[assignment (computer science)|assignment]]. Imperative programming does have functions—not in the mathematical sense—but in the sense of [[subroutine]]s. They can have [[side effect (computer science)|side effects]] that may change the value of program state. Functions without [[return value]]s therefore make sense. Because of this, they lack [[referential transparency (computer science)|referential transparency]], i.e. the same language expression can result in different values at different times depending on the state of the executing program.<ref name="hudak1989">{{cite journal | last = Hudak | first = Paul | authorlink = Paul Hudak | title = Conception, evolution, and application of functional programming languages | journal = [[Association for Computing Machinery|ACM]] Computing Surveys|volume=21|issue=3 | pages = 359–411 |date=September 1989 | url = http://www.dbnet.ece.ntua.gr/~adamo/languages/books/p359-hudak.pdf|format=PDF|doi=10.1145/72551.72554 }}</ref>
Functional programming languages have largely been emphasized in [[academic|academia]] rather than in commercial software development. However, prominent programming languages which support functional programming such as [[Common Lisp]], [[Scheme (programming language)|Scheme]],<ref name="clinger1987"/><ref name="hartheimer1987"/><ref name="kidd2007"/><ref name="cleis2006"/> [[Clojure]],<ref name="useR"/><ref name="Chambers"/> [[Wolfram Language]]<ref name="reference.wolfram.com">{{cite web | title = Wolfram Language Guide: Functional Programming | url = http://reference.wolfram.com/language/guide/FunctionalProgramming.html | year = 2015 | accessdate = 2015-08-24 }}</ref> (also known as [[Mathematica]]), [[Racket (programming language)|Racket]],<ref name="racket-video-games"/> [[Erlang (programming language)|Erlang]],<ref name="erlang-faq"/><ref name="armstrong2007"/><ref name="larson2009"/> [[OCaml]],<ref name="minksy2008"/><ref name="leroy2007"/> [[Haskell (programming language)|Haskell]],<ref name="haskell-industry"/><ref name="hudak2007"/> and [[F Sharp (programming language)|F#]]<ref name='quantFSharp'>{{cite conference | last = Mansell | first = Howard | title = Quantitative Finance in F# | url = http://cufp.galois.com/2008/abstracts.html#MansellHoward | year = 2008 | conference = CUFP 2008 | accessdate = 2009-08-29 }}</ref><ref name='businessAppsFSharp'>{{cite conference | last = Peake | first = Alex | title = The First Substantial Line of Business Application in F# | url = http://cufp.galois.com/2009/abstracts.html#AlexPeakeAdamGranicz | year = 2009 | conference = CUFP 2009 | accessdate = 2009-08-29 }}</ref> have been used in industrial and commercial applications by a wide variety of organizations. Functional programming is also supported in some [[___domain-specific programming language]]s like [[R (programming language)|R]] (statistics),<ref name="Amath-CO"/> [[J (programming language)|J]], [[K (programming language)|K]] and [[Q (programming language from Kx Systems)|Q from Kx Systems]] (financial analysis), [[XQuery]]/[[XSLT]] ([[XML]]),<ref name="Novatchev"/><ref name="Mertz"/> and Opal.<ref name="Opal (programming language)"/> Widespread ___domain-specific declarative languages like [[SQL]] and [[Lex (software)|Lex]]/[[Yacc]] use some elements of functional programming, especially in eschewing [[mutable object|mutable value]]s.<ref name="Chamberlin_Boyce"/>
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.<ref>{{cite book | last = Dominus | first = Mark J. | authorlink = Mark Jason Dominus | title = [[Higher-Order Perl]] |publisher=[[Morgan Kaufmann]] | year = 2005 |isbn = 1-55860-701-3 }}</ref> This is also true of the [[PHP]] programming language.<ref>{{cite book | last = Holywell | first = Simon | title = Functional Programming in PHP | publisher = php[architect] | year = 2014 | isbn = 9781940111056}}</ref> [[C++11]], [[Java programming|Java]] 8, and [[C Sharp (programming language)|C#]] 3.0 all added constructs to facilitate the functional style. The [[Julia (programming language)|Julia]] language also offers functional programming abilities. An interesting case is that of [[Scala (programming language)|Scala]]<ref name="effective-scala"/> – 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.
== History ==
[[Lambda calculus]] provides a theoretical framework for describing functions and their evaluation. Although it is a mathematical abstraction rather than a programming language, it forms the basis of almost all functional programming languages today. 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]].<ref>{{cite book|author1=Haskell Brooks Curry|author2=Robert Feys|title=Combinatory Logic|url=https://books.google.com/books?id=fEnuAAAAMAAJ|accessdate=10 February 2013|year=1958|publisher=North-Holland Publishing Company}}</ref>
An early functional-flavored language was [[Lisp (programming language)|Lisp]], developed in the late 1950s for the [[IBM 700/7000 series#Scientific Architecture|IBM 700/7000 series]] scientific computers by [[John McCarthy (computer scientist)|John McCarthy]] while at [[Massachusetts Institute of Technology]] (MIT).<ref>{{cite journal | first = John | last = McCarthy | authorlink = John McCarthy (computer scientist) | title = History of Lisp | journal = In [[Association for Computing Machinery|ACM]]/SIGPLAN History of Programming Languages Conference | pages = 217–223 |date=June 1978 | url = http://citeseer.ist.psu.edu/mccarthy78history.html|doi=10.1145/800025.808387 }}</ref> Lisp first introduced many paradigmatic features of functional programming, though early Lisps were [[Programming_paradigm#Multi-paradigm|multi-paradigm language]]s, and incorporated support for numerous programming styles as new paradigms evolved. Later dialects, such as [[Scheme (programming language)|Scheme]] and [[Clojure]], and offshoots such as [[Dylan (programming language)|Dylan]] and [[Julia (programming language)|Julia]], sought to simplify and rationalise Lisp around a cleanly functional core, while [[Common Lisp]] was designed to preserve and update the paradigmatic features of the numerous older dialects it replaced.<ref>{{cite journal|author1=Guy L. Steele |author2=Richard P. Gabriel |title=The Evolution of Lisp |journal= In [[Association for Computing Machinery|ACM]]/SIGPLAN Second History of Programming Languages |pages= 233-330 |date=February 1996 |url=http://dreamsongs.com/Files/HOPL2-Uncut.pdf |doi= 10.1145/234286.1057818 }}</ref>
[[Information Processing Language]] (IPL) is sometimes cited as the first computer-based functional programming language.<ref>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 which proved theorems from ''[[Principia Mathematica]]'' automatically. In order to accomplish this, they had to invent a language and a paradigm which, which viewed retrospectively, embeds functional programming.</ref> It is an [[assembly language|assembly-style language]] for manipulating lists of symbols. It does have a notion of "generator", which amounts to a function accepting a function as an argument, and, since it is an assembly-level language, code can be used as data, so IPL can be regarded as having higher-order functions. However, it relies heavily on mutating list structure and similar imperative features.
[[Kenneth E. Iverson]] developed [[APL (programming language)|APL]] in the early 1960s, described in his 1962 book ''A Programming Language'' (ISBN 9780471430148). APL was the primary influence on [[John Backus]]'s [[FP (programming language)|FP]]. In the early 1990s, Iverson and [[Roger Hui]] created [[J (programming language)|J]]. In the mid-1990s, [[Arthur Whitney (computer scientist)|Arthur Whitney]], who had previously worked with Iverson, created [[K (programming language)|K]], which is used commercially in financial industries along with its descendant [[Q (programming language from Kx Systems)|Q]].
[[John Backus]] presented [[FP (programming language)|FP]] in his 1977 [[Turing Award]] lecture "Can Programming Be Liberated From the [[Von Neumann architecture|von Neumann]] Style? A Functional Style and its Algebra of Programs".<ref>{{cite web|url=http://worrydream.com/refs/Backus-CanProgrammingBeLiberated.pdf|title=Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs|format=PDF}}</ref> He defines functional programs as being built up in a hierarchical way by means of "combining forms" that allow an "algebra of programs"; in modern language, this means that functional programs follow the [[principle of compositionality]]{{Citation needed|reason=I dont completely agree with this interpretation of John Backus definition of functional programs, which I feel is widely misunderstood. As he is very sadly no longer alive we can't ask him, but a reference for this interpretation, especially if it includes a justification, would be very beneficial.|date=February 2017}}. Backus's paper popularized research into functional programming, though it emphasized [[function-level programming]] rather than the lambda-calculus style which has come to be associated with functional programming.
In the 1970s, [[ML (programming language)|ML]] was created by [[Robin Milner]] at the [[University of Edinburgh]], and [[David Turner (computer scientist)|David Turner]] initially developed the language [[SASL (programming language)|SASL]] at the [[University of St Andrews]] and later the language [[Miranda (programming language)|Miranda]] at the [[University of Kent]]. Also in Edinburgh in the 1970s, Burstall and Darlington developed the functional language [[NPL (programming language)|NPL]].<ref>R.M. Burstall. Design considerations for a functional programming language. Invited paper, Proc. Infotech State of the Art Conf. "The Software Revolution", Copenhagen, 45–57 (1977)</ref> NPL was based on [[Kleene's recursion theorem|Kleene Recursion Equations]] and was first introduced in their work on program transformation.<ref>R.M. Burstall and J. Darlington. A transformation system for developing recursive programs. Journal of the Association for Computing Machinery 24(1):44–67 (1977)</ref> Burstall, MacQueen and Sannella then incorporated the polymorphic type checking from ML to produce the language [[Hope (programming language)|Hope]].<ref>R.M. Burstall, D.B. MacQueen and D.T. Sannella. HOPE: an experimental applicative language. Proc. 1980 LISP Conference, Stanford, 136–143 (1980).</ref> ML eventually developed into several dialects, the most common of which are now [[OCaml]] and [[Standard ML]]. Meanwhile, the development of [[Scheme (programming language)|Scheme]], a simple [[lexical scope|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.
In the 1980s, [[Per Martin-Löf]] developed [[intuitionistic type theory]] (also called ''constructive'' type theory), which associated functional programs with [[constructive proof]]s of arbitrarily complex mathematical propositions expressed as [[dependent type]]s. This led to powerful new approaches to [[interactive theorem proving]] and has influenced the development of many subsequent functional programming languages.
The [[Haskell (programming language)|Haskell language]] began with a consensus in 1987 to form an [[open standard]] for functional programming research; implementation releases have been ongoing since 1990.
== Concepts ==
A number of concepts and paradigms are specific to functional programming, and generally foreign to [[imperative programming]] (including [[object-oriented programming]]). However, programming languages are often hybrids of several programming paradigms, so programmers using "mostly imperative" languages may have utilized some of these concepts.<ref>{{cite web | url = http://byte.com/art/9408/sec11/art1.htm | archiveurl = https://web.archive.org/web/20060827094123/http://byte.com/art/9408/sec11/art1.htm | archivedate = 2006-08-27 | title = Functional Programming Comes of Age | author = Dick Pountain | work=BYTE.com (August 1994) | accessdate = August 31, 2006 }}</ref>
=== First-class and higher-order functions ===
{{main article|First-class function|Higher-order function}}
[[Higher-order function]]s are functions that can either take other functions as arguments or return them as results. In calculus, an example of a higher-order function is the [[differential operator]] <math>d/dx</math>, which returns the [[derivative]] of a function <math>f</math>.
Higher-order functions are closely related to [[first-class function]]s in that higher-order functions and first-class functions both allow functions as arguments and results of other functions. The distinction between the two is subtle: "higher-order" describes a mathematical concept of functions that operate on other functions, while "first-class" is a computer science term that describes programming language entities that have no restriction on their use (thus first-class functions can appear anywhere in the program that other first-class entities like numbers can, including as arguments to other functions and as their return values).
Higher-order functions enable [[partial application]] or [[currying]], a technique in which a function is applied to its arguments one at a time, with each application returning a new function that accepts the next argument. This allows one to succinctly express, for example, the [[successor function]] as the addition operator partially applied to the [[natural number]] one.
=== Pure functions ===
[[Pure function]]s (or expressions) have no [[side effect (computer science)|side effects]] (memory or I/O). This means that pure functions have several useful properties, many of which can be used to optimize the code:
* If the result of a pure expression is not used, it can be removed without affecting other expressions.
* 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 (computer science)|referential transparency]]), i.e. if the pure function is again called with the same arguments, the same result will be returned (this can enable caching optimizations such as [[memoization]]).
* If there is no data dependency between two pure expressions, then their order can be reversed, or they can be performed in [[parallelization|parallel]] and they cannot interfere with one another (in other terms, the evaluation of any pure expression is [[thread-safe]]).
* If the entire language does not allow side-effects, then any evaluation strategy can be used; this gives the compiler freedom to reorder or combine the evaluation of expressions in a program (for example, using [[deforestation (computer science)|deforestation]]).
While most compilers for imperative programming languages detect pure functions and perform common-subexpression elimination for pure function calls, they cannot always do this for pre-compiled libraries, which generally do not expose this information, thus preventing optimizations that involve those external functions. Some compilers, such as [[GNU Compiler Collection|gcc]], add extra keywords for a programmer to explicitly mark external functions as pure, to enable such optimizations. [[Fortran 95]] also allows functions to be designated "pure".
=== Recursion ===
{{Main article|Recursion (computer science)}}
[[Iteration]] (looping) in functional languages is usually accomplished via [[recursion]]. [[recursion (computer science)|Recursive function]]s invoke themselves, allowing an operation to be performed over and over until the [[Recursion (computer science)|base case]] is reached. 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 (programming language)|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.
Common patterns of recursion can be factored out using higher order functions, with [[catamorphism]]s and [[anamorphism]]s (or "folds" and "unfolds") being the most obvious examples. Such higher order functions play a role analogous to built-in control structures such as [[Program loops|loops]] in [[imperative languages]].
Most general purpose functional programming languages allow unrestricted recursion and are [[Turing complete]], which makes the [[halting problem]] [[undecidable problem|undecidable]], can cause unsoundness of [[equational reasoning]], and generally requires the introduction of [[inconsistency]] into the logic expressed by the language's [[type system]]. Some special purpose languages such as [[Coq]] allow only [[well-founded]] recursion and are [[strongly normalizing]] (nonterminating computations can be expressed only with infinite streams of values called [[codata (computer science)|codata]]). As a consequence, these languages fail to be Turing complete and expressing certain functions in them is impossible, but they can still express a wide class of interesting computations while avoiding the problems introduced by unrestricted recursion. Functional programming limited to well-founded recursion with a few other constraints is called [[total functional programming]].<ref name=totalfp>{{cite journal | last = Turner | first = D.A.|author-link=David Turner (computer scientist) | title = Total Functional Programming | journal = Journal of Universal Computer Science|volume=10| date = 2004-07-28 | pages = 751–768 | url = http://www.jucs.org/jucs_10_7/total_functional_programming|doi=10.3217/jucs-010-07-0751|issue=7}}</ref>
=== Strict versus non-strict evaluation ===
{{Main article|Evaluation strategy}}
Functional languages can be categorized by whether they use ''strict (eager)'' or ''non-strict (lazy)'' evaluation, concepts that refer to how function arguments are processed when an expression is being evaluated. The technical difference is in the [[denotational semantics]] of expressions containing failing or divergent computations. Under strict evaluation, the evaluation of any term containing a failing subterm will itself fail. For example, the expression:
<!-- language? -->
print length([2+1, 3*2, 1/0, 5-4])
will fail under strict evaluation because of the division by zero in the third element of the list. Under lazy evaluation, the length function will return the value 4 (i.e., the number of items in the list), since evaluating it will 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]].<ref>[http://research.microsoft.com/~simonpj/papers/slpj-book-1987/index.htm The Implementation of Functional Programming Languages]. Simon Peyton Jones, published by Prentice Hall, 1987</ref> Lazy evaluation is used by default in several pure functional languages, including [[Miranda (programming language)|Miranda]], [[Clean (programming language)|Clean]], and [[Haskell (programming language)|Haskell]].
{{Harvnb|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.<ref>{{cite web |url=http://www.cse.chalmers.se/~rjmh/Papers/whyfp.html |title=Why Functional Programming Matters |authorlink=John Hughes (computer scientist) |first=John |last=Hughes |year=1984 |ref=harv}}</ref> Launchbury 1993 <!-- a cite arguing more strongly against lazy evaluation would be preferable here, if someone knows of one. --> 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.<ref name=launchbury1993>{{cite web | url = http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.35.2016 | author = John Launchbury | title = A Natural Semantics for Lazy Evaluation | year = 1993 }}</ref> Harper 2009 proposes including both strict and lazy evaluation in the same language, using the language's type system to distinguish them.<ref>{{cite book | url = http://www.cs.cmu.edu/~rwh/plbook/book.pdf | title = Practical Foundations for Programming Languages | author = Robert W. Harper | authorlink=Robert_Harper_(computer_scientist) | year = 2009 }}</ref>
=== Type systems ===
<!-- expand this section!!! also split it into several sections -->
Especially since the development of [[Hindley–Milner type inference]] in the 1970s, functional programming languages have tended to use [[typed lambda calculus]], rejecting all invalid programs at compilation time and risking [[false positives and false negatives#False positive error|false positive errors]], as opposed to the [[untyped lambda calculus]], that accepts all valid programs at compilation time and risks [[false positives and false negatives#False negative error|false negative errors]], used in Lisp and its variants (such as [[Scheme (programming language)|Scheme]]), although they reject all invalid programs at runtime, when the information is enough to not reject valid programs. The use of [[algebraic datatypes]] makes manipulation of complex data structures convenient; the presence of strong compile-time type checking makes programs more reliable in absence of other reliability techniques like [[test-driven development]], while [[type inference]] frees the programmer from the need to manually declare types to the compiler in most cases.
Some research-oriented functional languages such as [[Coq]], [[Agda (theorem prover)|Agda]], [[Cayenne (programming language)|Cayenne]], and [[Epigram (programming language)|Epigram]] are based on [[intuitionistic type theory]], which allows types to depend on terms. Such types are called [[dependent type]]s. These type systems do not have decidable type inference and are difficult to understand and program with{{Citation needed| date = December 2011}}. But dependent types can express arbitrary propositions in [[predicate logic]]. Through the [[Curry–Howard isomorphism]], then, well-typed programs in these languages become a means of writing formal [[mathematical proof]]s from which a compiler can generate [[formal verification|certified code]]. While these languages are mainly of interest in academic research (including in [[formalized mathematics]]), they have begun to be used in engineering as well. [[Compcert]] is a [[compiler]] for a subset of the [[C (programming language)|C programming language]] that is written in Coq and formally verified.<ref>{{cite web | url = http://compcert.inria.fr/doc/index.html | title = The Compcert verified compiler }}</ref>
A limited form of dependent types called [[generalized algebraic data type]]s (GADT's) can be implemented in a way that provides some of the benefits of dependently typed programming while avoiding most of its inconvenience.<ref>{{cite web | url = http://research.microsoft.com/en-us/um/people/simonpj/papers/gadt/ | title = Simple unification-based type inference for GADTs |author1=Simon Peyton Jones |author2=Dimitrios Vytiniotis |author3=Stephanie Weirich |author4=Geoffrey Washburn | work=ICFP 2006 | pages = 50–61 }}</ref> GADT's are available in the [[Glasgow Haskell Compiler]], in [[OCaml]] (since version 4.00) and in [[Scala (programming language)|Scala]] (as "case classes"), and have been proposed as additions to other languages including Java and C#.<ref>{{cite web | title = Generalized Algebraic Data Types and Object-Oriented Programming |author1=Andrew Kennedy |author2=Claudio Russo | work=OOPSLA | date = October 2005 | ___location = San Diego, California | url = http://research.microsoft.com/~akenn/generics/gadtoop.pdf | archiveurl = https://web.archive.org/web/20061229164852/http://research.microsoft.com/~akenn/generics/gadtoop.pdf | archivedate = 2006-12-29 }} [http://lambda-the-ultimate.org/node/1134 source of citation]</ref>
=== Referential transparency ===
{{Main article|Referential transparency}}
Functional programs do not have assignment statements, that is, the value of a variable in a functional program never changes once defined. This eliminates any chances of side effects because any variable can be replaced with its actual value at any point of execution. So, functional programs are referentially transparent.<ref>{{cite web|last1=Huges|first1=John|title=Why Functional Programming Matters|url=http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf|website=http://www.chalmers.se/cse|publisher=Chalmers Tekniska H¨ogskola}}</ref>
Consider [[C (programming language)|C]] assignment statement <code>x = x * 10</code>, this changes the value assigned to the variable <code>x</code>. Let us say that the initial value of <code>x</code> was <code>1</code>, then two consecutive evaluations of the variable <code>x</code> will yield <code>10</code> and <code>100</code> respectively. Clearly, replacing <code>x = x * 10</code> with either <code>10</code> or <code>100</code> gives a program with different meaning, and so the expression ''is not'' referentially transparent. In fact, assignment statements are never referentially transparent.
Now, consider another function such as <code>int plusone(int x) {return x+1;}</code> ''is'' transparent, as it will not implicitly change the input x and thus has no such [[side effect (computer science)|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.<ref>{{cite journal | last = Hartel | first = Pieter |author2=Henk Muller |author3=Hugh Glaser | title = The Functional C experience | journal = Journal of Functional Programming | volume=14 |issue=2 | pages = 129–135 |date=March 2004 | url = http://www.ub.utwente.nl/webdocs/ctit/1/00000084.pdf |format=PDF| doi=10.1017/S0956796803004817}}; {{cite web | title = Functional programming in Python, Part 3 | url = http://www-128.ibm.com/developerworks/linux/library/l-prog3.html | archiveurl = http://wayback.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog3.html | archivedate = 2007-10-16 | author = David Mertz | accessdate = 2006-09-17 | work=IBM developerWorks}}([http://wayback.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog.html Part 1], [http://wayback.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog2.html Part 2])</ref> For example, both [[D (programming language)|D]] and [[Fortran 95]] explicitly support pure functions.<ref>{{cite web | url = http://www.digitalmars.com/d/2.0/function.html#pure-functions | title = Functions — D Programming Language 2.0 |publisher=Digital Mars | accessdate = 2011-06-20 }}</ref>
[[JavaScript]], [[Lua (programming language)|Lua]]<ref>{{cite web|url=http://www.luafaq.org/#T1.2|title=Lua Unofficial FAQ (uFAQ)|publisher=}}</ref> and [[Python (programming language)|Python]] had [[First-class function|first class functions]] from their inception.<ref>{{cite web|url=https://brendaneich.com/2008/04/popularity/|title=Brendan Eich|publisher=}}</ref> Amrit Prem added support to Python for "[[anonymous function|lambda]]", "[[Map (higher-order function)|map]]", "[[Fold (higher-order function)|reduce]]", and "[[Filter (higher-order function)|filter]]" in 1994, as well as closures in Python 2.2,<ref>{{cite web |url=http://python-history.blogspot.de/2009/04/origins-of-pythons-functional-features.html |title=Origins of Python's "Functional" Features |last=van Rossum |first=Guido |authorlink=Guido van Rossum |publisher=[http://python-history.blogspot.de/ The History of Python] |date=2009-04-21 |accessdate=2012-09-27 }}</ref> though Python 3 relegated "reduce" to the <code>functools</code> standard library module.<ref>{{cite web | url = https://docs.python.org/dev/library/functools.html#functools.reduce | title = functools — Higher order functions and operations on callable objects | publisher=Python Software Foundation | date = 2011-07-31 | accessdate = 2011-07-31}}</ref> First-class functions have been introduced into other mainstream languages such as [[PHP]] 5.3, [[Visual Basic]] 9, [[C Sharp (programming language)|C#]] 3.0, and [[C++11]].{{citation needed|date=April 2015}}
In [[Java (programming language)|Java]], [[anonymous class]]es can sometimes be used to simulate [[Closure (computer science)|closure]]s;<ref>{{cite book | last = Skarsaune | first = Martin | title = The SICS Java Port Project Automatic Translation of a Large Object Oriented System from Smalltalk to Java | year = 2008 }}</ref> however, anonymous classes are not always proper replacements to [[Closure (computer science)|closure]]s because they have more limited capabilities.<ref>{{cite web|last=Gosling|first=James|title=Closures|url=http://blogs.oracle.com/jag/entry/closures|work=James Gosling: on the Java Road|publisher=Oracle|accessdate=11 May 2013}}</ref> Java 8 supports lambda expressions as a replacement for some anonymous classes.<ref>{{cite web|url=https://blogs.oracle.com/javatraining/entry/java_se_8_lambda_quick|title=Java SE 8 Lambda Quick Start}}</ref> 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|date=March 2014}}
In [[C Sharp (programming language)|C#]], [[anonymous class]]es are not necessary, because [[Closure (computer science)|closure]]s and lambdas are fully supported. Libraries and language extensions for immutable data structures are being developed to aid programming in the functional style in C#.
Many [[object-oriented]] [[Design pattern (computer science)|design pattern]]s are expressible in functional programming terms: for example, the [[strategy pattern]] simply dictates use of a higher-order function, and the [[visitor (design pattern)|visitor]] pattern roughly corresponds to a [[catamorphism]], or [[fold (higher-order function)|fold]].
Similarly, the idea of immutable data from functional programming is often included in imperative programming languages,<ref>{{cite book | title = Effective Java | edition = Second | first = Joshua | last = Bloch | pages = Item 15 }}</ref> for example the tuple in Python, which is an immutable array.
===Data structures===
{{main article|Purely functional data structure}}
Purely functional [[data structure]]s are often represented in a different way than their [[imperative programming|imperative]] counterparts.<ref>[http://www.cambridge.org/us/academic/subjects/computer-science/algorithmics-complexity-computer-algebra-and-computational-g/purely-functional-data-structures ''Purely functional data structures''] by [[Chris Okasaki]], [[Cambridge University Press]], 1998, ISBN 0-521-66350-4</ref> For example, [[array data structure|array]] with constant-time access and update is a basic component of most imperative languages and many imperative data-structure, such as [[hash table]] and [[binary heap]], are based on arrays. Arrays can be replaced by [[Map (computer science)|map]] or [[random access list]], which admits purely functional implementation, but the access and update time is [[logarithm]]ic. Therefore, purely functional data structures can be used in languages which are non-functional, but they may not be the most efficient tool available, especially if persistency is not required.
== Comparison to imperative programming ==
Functional programming is very different from [[imperative programming]]. The most significant differences stem from the fact that functional programming avoids [[side effect (computer science)|side effects]], which are used in imperative programming to implement state and I/O. Pure functional programming completely prevents side-effects and provides [[referential transparency (computer science)|referential transparency]].
Higher-order functions are rarely used in older imperative programming. A traditional imperative program might use a loop to traverse and modify a list. A functional program, on the other hand, would probably use a higher-order “map” function that takes a function and a list, generating and returning a new list by applying the function to each list item.
=== Simulating state ===
There are tasks (for example, maintaining a bank account balance) that often seem most naturally implemented with state. Pure functional programming performs these tasks, and I/O tasks such as accepting user input and printing to the screen, in a different way.
The pure functional programming language [[Haskell (programming language)|Haskell]] implements them using [[monad (functional programming)|monads]], derived from [[category theory]]. Monads offer a way to abstract certain types of computational patterns, including (but not limited to) modeling of computations with mutable state (and other side effects such as I/O) in an imperative manner without losing purity. While existing monads may be easy to apply in a program, given appropriate templates and examples, many students find them difficult to understand conceptually, e.g., when asked to define new monads (which is sometimes needed for certain types of libraries).<ref>{{cite web | last = Newbern | first = J. | title = All About Monads: A comprehensive guide to the theory and practice of monadic programming in Haskell | url = http://monads.haskell.cz/html/index.html/html/ | accessdate = 2008-02-14 }}</ref>
Another way in which functional languages can simulate state is by passing around a [[data structure]] that represents the current state as a parameter to function calls. On each function call, a copy of this data structure is created with whatever differences are the result of the function. This is referred to as '[[state-passing style]]'.
<!-- TO DO: Expand -->
Impure functional languages usually include a more direct method of managing mutable state. [[Clojure]], for example, uses managed references that can be updated by applying pure functions to the current state. This kind of approach enables mutability while still promoting the use of pure functions as the preferred way to express computations.
<!-- TO DO: Expand / example code?? -->
Alternative methods such as [[Hoare logic]] and [[uniqueness type|uniqueness]] have been developed to track side effects in programs. Some modern research languages use [[effect system]]s to make the presence of side effects explicit.
<!-- TO DO: Expand -->
=== Efficiency issues ===
Functional programming languages are typically less efficient in their use of [[central processing unit|CPU]] and memory than imperative languages such as [[C (programming language)|C]] and [[Pascal (programming language)|Pascal]].<ref>{{cite book|author=Larry C. Paulson|title=ML for the Working Programmer|url=https://books.google.com/books?id=XppZdaDs7e0C|accessdate=10 February 2013|date=28 June 1996|publisher=Cambridge University Press|isbn=978-0-521-56543-1}}</ref> <!-- Paulson mentions the reputation for inefficiency in Sec. 1.5; perhaps a more in-depth discussion could be found. --> 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. <!-- perhaps this could be formulated by someone who knows the subject, I was simply curious about unexplained statement "logarithmic slowdown" --> 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).<ref name="Spiewak"/> However, such slowdowns are not universal. For programs that perform intensive numerical computations, functional languages such as [[OCaml]] and [[Clean (programming language)|Clean]] are only slightly slower than C.<ref>{{cite web | url = http://benchmarksgame.alioth.debian.org/u32/which-programs-are-fastest.php?gcc=on&ghc=on&clean=on&ocaml=on&sbcl=on&fsharp=on&racket=on&clojure=on&hipe=on&calc=chart | title = Which programs are fastest? | Computer Language Benchmarks Game | publisher=benchmarksgame.alioth.debian.org | accessdate = 2011-06-20 }}</ref> For programs that handle large [[matrix (mathematics)|matrices]] and multidimensional [[database]]s, [[array programming|array]] functional languages (such as [[J (programming language)|J]] and [[K (programming language)|K]]) were designed with speed optimizations.
Immutability of data can in many cases lead to execution efficiency by allowing the compiler to make assumptions that are unsafe in an imperative language, thus increasing opportunities for [[inline expansion]].<ref>{{cite journal | title = Immutability specification and its applications |author1=Igor Pechtchanski |author2=Vivek Sarkar | journal = Concurrency and Computation: Practice and Experience | volume = 17 | issue = 5–6 | pages = 639–662 | year = 2005 | doi = 10.1002/cpe.853 }}</ref>
[[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 leak]]s if used improperly). Launchbury 1993<ref name=launchbury1993/> discusses theoretical issues related to memory leaks from lazy evaluation, and O'Sullivan ''et al.'' 2008<ref>{{cite web | url = http://book.realworldhaskell.org/read/profiling-and-optimization.html#x_eK1 | title = Chapter 25. Profiling and optimization |publisher=Book.realworldhaskell.org | accessdate = 2011-06-20 }}</ref> 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|date=June 2014}}.
=== Coding styles ===
{{unreferenced section|date=July 2013}}
Imperative programs have the environment and a sequence of steps manipulating the environment. Functional programs have an expression that is successively substituted until it reaches normal form. An example illustrates this with different solutions to the same programming goal (calculating [[Fibonacci number]]s).
====[[Python (programming language)|Python]]====
Printing first 10 Fibonacci numbers, iterative
<source lang="python">
def fibonacci(n, first=0, second=1):
while n != 0:
print(first, end="\n") # side-effect
n, first, second = n - 1, second, first + second # assignment
fibonacci(10)
</source>
Printing first 10 Fibonacci numbers, functional expression style
<source lang="python">
fibonacci = (lambda n, first=0, second=1:
"" if n == 0 else
str(first) + "\n" + fibonacci(n - 1, second, first + second))
print(fibonacci(10), end="")
</source>
Printing a list with first 10 Fibonacci numbers, with generators
<source lang="python">
def fibonacci(n, first=0, second=1):
while n != 0:
yield first
n, first, second = n - 1, second, first + second # assignment
print(list(fibonacci(10)))
</source>
Printing a list with first 10 Fibonacci numbers, functional expression style
<source lang="python">
fibonacci = (lambda n, first=0, second=1:
[] if n == 0 else
[first] + fibonacci(n - 1, second, first + second))
print(fibonacci(10))
</source>
====[[Haskell (programming language)|Haskell]]====
Printing first 10 Fibonacci numbers, functional expression style<ref name="expression style" />
<source lang="haskell">
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)
</source>
Printing a list with first 10 Fibonacci numbers, functional expression style<ref name="expression style" />
<source lang="haskell">
fibonacci_aux = \n first second->
if n == 0 then [] else
[first] ++ fibonacci_aux (n - 1) second (first + second)
fibonacci = \n-> fibonacci_aux n 0 1
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" />
<source lang="haskell">
fibonacci = \n-> if n == 0 then 0
else if n == 1 then 1
else fibonacci(n - 1) + fibonacci(n - 2)
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style,<ref name="expression style" /> [[tail recursive]]
<source lang="haskell">
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))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" /> with recursive lists
<source lang="haskell">
fibonacci_aux = \first second-> first : fibonacci_aux second (first + second)
select = \n zs-> if n==0 then head zs
else select (n - 1) (tail zs)
fibonacci = \n-> select n (fibonacci_aux 0 1)
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" /> with primitives for recursive lists
<source lang="haskell">
fibonacci_aux = \first second-> first : fibonacci_aux second (first + second)
fibonacci = \n-> (fibonacci_aux 0 1) !! n
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" /> with primitives for recursive lists, more concisely
<source lang="haskell">
fibonacci_aux = 0:1:zipWith (+) fibonacci_aux (tail fibonacci_aux)
fibonacci = \n-> fibonacci_aux !! n
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional declaration style,<ref name="declaration style" /> [[tail recursive]]
<source lang="haskell">
fibonacci_aux 0 first _ = first
fibonacci_aux n first second = fibonacci_aux (n - 1) second (first + second)
fibonacci n = fibonacci_aux n 0 1
main = putStrLn (show (fibonacci 10))
</source>Printing the 11th Fibonacci number, functional declaration style, using [[Lazy evaluation|lazy]] [[Lazy evaluation|infinite lists]] and primitives<syntaxhighlight lang="haskell">
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
-- an infinite list of the fibonacci numbers
-- fibs is defined in terms of fibs
fibonacci = (fibs !!)
main = putStrLn $ show $ fibonacci 11
</syntaxhighlight>
====Perl 6====
As influenced by Haskell and others, [[Perl 6]] has several functional and declarative approaches to problems. For example, you can declaratively build up a well-typed recursive version (the type constraints are optional) through signature pattern matching:
<source lang="perl6">
subset NonNegativeInt of Int where * >= 0;
proto fib (|) is cached returns NonNegativeInt {*}
multi fib (0) { 0 }
multi fib (1) { 1 }
multi fib (NonNegativeInt $n) { fib($n - 1) + fib($n - 2) }
for ^10 -> $n { say fib($n) }
</source>
An alternative to this is to construct a lazy iterative sequence, which appears as an almost direct illustration of the sequence:
<source lang="perl6">
my @fib = 0, 1, *+* ... *; # Each additional entry is the sum of the previous two
# and this sequence extends lazily indefinitely
say @fib[^10]; # Display the first 10 entries
</source>
====[[Erlang (programming language)|Erlang]]====
'''[[Erlang (programming language)|Erlang]]''' is a functional, concurrent, general-purpose programming language. A [[Fibonacci number|Fibonacci]] algorithm implemented in Erlang (Note: This is only for demonstrating the Erlang [[Syntax (programming languages)|syntax]]. Use other algorithms for fast performance<ref>[http://www.aquabu.com/2008/02/16/fibonacci-sequence-recursion-in-erlang/]{{dead link|date=February 2016}}</ref>):
<source lang="erlang">
-module(fib). % This is the file 'fib.erl', the module and the filename must match
-export([fib/1]). % This exports the function 'fib' of arity 1
fib(1) -> 1; % If 1, then return 1, otherwise (note the semicolon ; meaning 'else')
fib(2) -> 1; % If 2, then return 1, otherwise
fib(N) -> fib(N - 2) + fib(N - 1).
</source>
==== Elixir ====
'''[[Elixir (programming language)|Elixir]]''' is a functional, concurrent, general-purpose programming language that runs on the [[Erlang (programming language)|Erlang virtual machine (BEAM)]].
The Fibonacci function can be written in Elixir as follows:<syntaxhighlight lang="elixir">
defmodule Fibonacci do
def fib(0), do: 0
def fib(1), do: 1
def fib(n), do: fib(n-1) + fib(n-2)
end
</syntaxhighlight>
====Lisp====
The Fibonacci function can be written in [[Common Lisp]] as follows:
<source lang="lisp">
(defun fib (n &optional (a 0) (b 1))
(if (= n 0)
a
(fib (- n 1) b (+ a b))))
</source>
The program can then be called as
<source lang="lisp">
(fib 10)
</source>
====[[Clojure]]====
The Fibonacci function can be written in [[Clojure]] as follows:
<source lang="clojure">
(defn fib
[n]
(loop [a 0 b 1 i n]
(if (zero? i)
a
(recur b (+ a b) (dec i)))))
</source>
The program can then be called as
<source lang="clojure">
(fib 7)
</source>
====D====
[[D (programming language)|D]] has support for functional programming{{clarify|date=April 2015}}{{citation needed|date=April 2015}}:
<source lang="d">
import std.stdio;
import std.range;
void main()
{
/* 'f' is a range representing the first 10 Fibonacci numbers */
auto f = recurrence!((seq, i) => seq[0] + seq[1])(0, 1)
.take(10);
writeln(f);
}
</source>
====R====
[[R (programming language)|R]] is an environment for statistical computing and graphics. It is also a functional programming language.
The Fibonacci function can be written in [[R (programming language)|R]] as a recursive function as follows:
<source lang="rsplus">
fib <- function(n) {
if (n <= 2) 1
else fib(n - 1) + fib(n - 2)
}
</source>
Or it can be written as a singly recursive function:
<source lang="rsplus">
fib <- function(n,a=1,b=1) {
if (n == 1) a
else fib(n-1,b,a+b)
}
</source>
Or it can be written as an iterative function:
<source lang="rsplus">
fib <- function(n) {
if (n == 1) 1
else if (n == 2) 1
else {
fib<-c(1,1)
for (i in 3:n) fib<-c(0,fib[1])+fib[2]
fib[2]
}
}
</source>
The function can then be called as
<source lang="rsplus">
fib(10)
</source>
====[[SequenceL]]====
SequenceL is a functional, concurrent, general-purpose programming language. The Fibonacci function can be written in SequenceL as follows:
<source lang="haskell">
fib(n) := n when n < 2 else
fib(n - 1) + fib(n - 2);
</source>
The function can then be called as
<source lang="haskell">
fib(10)
</source>
To reduce the memory consumed by the call stack when computing a large Fibonacci term, a tail-recursive version can be used. A tail-recursive function is implemented by the SequenceL compiler as a memory-efficient looping structure:
<source lang="haskell">
fib(n) := fib_Helper(0, 1, n);
fib_Helper(prev, next, n) :=
prev when n < 1 else
next when n = 1 else
fib_Helper(next, next + prev, n - 1);
</source>
== Use in industry ==
Functional programming has long been popular in academia, but with few industrial applications.<ref name='programmingScala'>{{cite book | first1 = Martin | last1 = Odersky | first2 = Lex | last2 = Spoon | first3 = Bill | last3 = Venners | date = December 13, 2010 | title = Programming in Scala: A Comprehensive Step-by-step Guide | publisher = [[Artima Inc]] | edition = 2nd | pages = 883/852 | isbn = 978-0-9815316-4-9 | url = http://www.artima.com/shop/programming_in_scala_2ed }}</ref>{{rp|page 11}} However, recently several prominent functional programming languages have been used in commercial or industrial systems. For example, the [[Erlang (programming language)|Erlang]] programming language, which was developed by the [[Sweden|Swedish]] company [[Ericsson]] in the late 1980s, was originally used to implement fault-tolerant telecommunications systems.<ref name="armstrong2007"/> It has since become popular for building a range of applications at companies such as [[T-Mobile]], [[Nortel]], [[Facebook]], [[Électricité de France]] and [[WhatsApp]].<ref name="erlang-faq"/><ref name="larson2009"/><ref>{{cite conference | last = Piro | first = Christopher | title = Functional Programming at Facebook | url = http://cufp.galois.com/2009/abstracts.html#ChristopherPiroEugeneLetuchy | year = 2009 | conference = CUFP 2009 | accessdate = 2009-08-29 }}</ref><ref name="Sim-Diasca"/><ref name="whatsapp.blog.2012">[http://blog.whatsapp.com/index.php/2012/01/1-million-is-so-2011/ 1 million is so 2011] // WhatsApp blog, 2012-01-06: "the last important piece of our infrastracture is Erlang"</ref> The [[Scheme (programming language)|Scheme]] dialect of [[Lisp (programming language)|Lisp]] was used as the basis for several applications on early [[Apple Macintosh]] computers,<ref name="clinger1987"/><ref name="hartheimer1987"/> and has more recently been applied to problems such as training [[Computer simulation|simulation software]]<ref name="kidd2007"/> and [[telescope]] control.<ref name="cleis2006"/> [[OCaml]], which was introduced in the mid-1990s, has seen commercial use in areas such as financial analysis,<ref name="minksy2008"/> [[software driver|driver]] verification, industrial [[robot]] programming, and static analysis of [[embedded software]].<ref name="leroy2007"/> [[Haskell (programming language)|Haskell]], although initially intended as a research language,<ref name="hudak2007"/> has also been applied by a range of companies, in areas such as aerospace systems, hardware design, and web programming.<ref name="haskell-industry"/><ref name="hudak2007"/>
Other functional programming languages that have seen use in industry include [[Scala (programming language)|Scala]],<ref>{{cite conference | last = Momtahan | first = Lee | title = Scala at EDF Trading: Implementing a Domain-Specific Language for Derivative Pricing with Scala | url = http://cufp.galois.com/2009/abstracts.html#LeeMomtahan | year = 2009 | conference = CUFP 2009 | accessdate = 2009-08-29 }}</ref> [[F Sharp (programming language)|F#]],<ref name='quantFSharp'/><ref name='businessAppsFSharp'/> (both being functional-OO hybrids with support for both purely functional and imperative programming) [[Wolfram Language]],<ref name="reference.wolfram.com"/> [[Lisp (programming language)|Lisp]],<ref>{{cite web | last = Graham | first = Paul | title = Beating the Averages | url = http://www.paulgraham.com/avg.html | year = 2003 | accessdate = 2009-08-29 }}</ref> [[Standard ML]]<ref>{{cite conference | last = Sims | first = Steve | title = Building a Startup with Standard ML | url = http://cufp.galois.com/2006/slides/SteveSims.pdf | year = 2006 | conference = CUFP 2006 | accessdate = 2009-08-29 }}</ref><ref>{{cite conference | last = Laurikari | first = Ville | title = Functional Programming in Communications Security. | url = http://cufp.galois.com/2007/abstracts.html#VilleLaurikari | year = 2007 | conference = CUFP 2007 | accessdate = 2009-08-29 }}</ref> and [[Clojure]].<ref>{{cite web | url = http://www.infoq.com/news/2009/01/clojure_production | last = Lorimer | first = R. J. | title = Live Production Clojure Application Announced }}</ref>
==In education==
Functional programming is being used as a method to teach problem solving, algebra and geometric concepts.<ref name="bootstrapworld">{{Triangulation|196|Emmanuel Schanzer of Bootstrap}}</ref>
It has also been used as a tool to teach classical mechanics in [[Structure and Interpretation of Classical Mechanics]].
== See also ==
{{Portal|Computer programming}}
* [[Purely functional programming]]
* [[Comparison of programming paradigms]]
* [[Eager evaluation]]
* [[List of functional programming topics]]
* [[Nested function]]
* [[Inductive functional programming]]
* [[Functional reactive programming]]
== References ==
{{reflist|colwidth=30em|refs=
<ref name="clinger1987">{{cite journal | last = Clinger | first = Will | title = MultiTasking and MacScheme | magazine = MacTech | volume = 3 | issue = 12 | year = 1987 | url = http://www.mactech.com/articles/mactech/Vol.03/03.12/Multitasking/index.html | accessdate = 2008-08-28 }}</ref>
<ref name="hartheimer1987">{{cite journal | last = Hartheimer | first = Anne | title = Programming a Text Editor in MacScheme+Toolsmith | magazine = MacTech | volume = 3 | issue = 1 | year = 1987 | url = http://www.mactech.com/articles/mactech/Vol.03/03.1/SchemeWindows/index.html | accessdate = 2008-08-28 }}</ref>
<ref name="kidd2007">{{cite conference | last = Kidd | first = Eric | url = http://cufp.galois.com/2007/abstracts.html#EricKidd | title = Terrorism Response Training in Scheme | conference = CUFP 2007 | accessdate = 2009-08-26 }}</ref>
<ref name="cleis2006">{{cite conference | last = Cleis | first = Richard | url = http://cufp.galois.com/2006/abstracts.html#RichardCleis | title = Scheme in Space | conference = CUFP 2006 | accessdate = 2009-08-26 }}</ref>
<ref name="erlang-faq">{{cite web | title = Who uses Erlang for product development? | work=Frequently asked questions about Erlang | url = http://www.erlang.org/faq/faq.html#AEN50 | accessdate = 2007-08-05 }}</ref>
<ref name="armstrong2007">{{cite conference | last = Armstrong | first = Joe | title = A history of Erlang | conference = Third ACM SIGPLAN Conference on History of Programming Languages | ___location = San Diego, California | date = June 2007 | url = http://doi.acm.org/10.1145/1238844.1238850 | accessdate = 2009-08-29 }}</ref>
<ref name="larson2009">{{cite journal | last = Larson | first = Jim | title = Erlang for concurrent programming | journal = Communications of the ACM | volume= 52 | issue= 3 | date = March 2009 | doi=10.1145/1467247.1467263 | page=48 }}</ref>
<ref name="minksy2008">{{cite journal | last = Minsky | first = Yaron | last2 = Weeks | first2 = Stephen | title = Caml Trading — experiences with functional programming on Wall Street | journal = Journal of Functional Programming | volume = 18 | issue = 4 | pages = 553–564 | publisher = Cambridge University Press | ___location = |date=July 2008 | url = http://journals.cambridge.org/action/displayAbstract?aid=1899164 | doi = 10.1017/S095679680800676X | accessdate = 2008-08-27 }}</ref>
<ref name="leroy2007">{{cite conference | last = Leroy | first = Xavier | title = Some uses of Caml in Industry | url = http://cufp.galois.com/2007/slides/XavierLeroy.pdf | conference = CUFP 2007 | accessdate = 2009-08-26 }}</ref><ref name="haskell-industry">{{cite web | title = Haskell in industry | work = Haskell Wiki | url = http://www.haskell.org/haskellwiki/Haskell_in_industry | accessdate = 2009-08-26 | quote=Haskell has a diverse range of use commercially, from aerospace and defense, to finance, to web startups, hardware design firms and lawnmower manufacturers. }}</ref>
<ref name="effective-scala">{{cite web | title = Effective Scala | work = Scala Wiki | url = http://twitter.github.com/effectivescala/?sd | accessdate = 2012-02-21 | quote=Effective Scala. }}</ref><ref name="racket-video-games">{{cite web | title = State-Based Scripting in Uncharted 2 | url = http://www.gameenginebook.com/gdc09-statescripting-uncharted2.pdf | archiveurl = https://web.archive.org/web/20121215014637/http://www.gameenginebook.com/gdc09-statescripting-uncharted2.pdf | archivedate = 2012-12-15 | accessdate = 2011-08-08 }}</ref>
<ref name="hudak2007">{{cite conference | last = Hudak | first = Paul |author2=Hughes, J. |author3=Jones, S. P. |author4=Wadler, P. | authorlink=Paul Hudak | title = A history of Haskell: being lazy with class | url=http://dl.acm.org/citation.cfm?doid=1238844.1238856 | conference = Third ACM SIGPLAN Conference on History of Programming Languages | ___location = San Diego, California| date = June 2007 | doi = 10.1145/1238844.1238856 | accessdate = 2013-09-26 }}</ref>
<ref name="useR">{{cite web | url = http://www.r-project.org/useR-2006/program.html | title = The useR! 2006 conference schedule includes papers on the commercial use of R |publisher=R-project.org | date = 2006-06-08 | accessdate = 2011-06-20 }}</ref><ref name="Chambers">{{cite book | last = Chambers | first = John M. | authorlink=John Chambers (programmer) | title = Programming with Data: A Guide to the S Language | publisher=Springer Verlag | year = 1998 | pages = 67–70 | isbn = 978-0-387-98503-9 }}</ref><ref name="Amath-CO">{{cite web | author = Department of Applied Math, University of Colorado | title = Functional vs. Procedural Programming Language | url = http://amath.colorado.edu/computing/mmm/funcproc.html | archiveurl = https://web.archive.org/web/20071113175801/http://amath.colorado.edu/computing/mmm/funcproc.html | archivedate = 2007-11-13 | accessdate = 2006-08-28 }}</ref>
<ref name="Novatchev">{{cite web | url = http://www.topxml.com/xsl/articles/fp/ | author = Dimitre Novatchev | title = The Functional Programming Language XSLT — A proof through examples | accessdate = May 27, 2006 | work=TopXML }}</ref><ref name="Mertz">{{cite web | url = http://gnosis.cx/publish/programming/xml_models_fp.html | author = David Mertz | title = XML Programming Paradigms (part four): Functional Programming approached to XML processing | accessdate = May 27, 2006 | work=IBM developerWorks }}</ref>
<ref name="Chamberlin_Boyce">{{cite journal | title = SEQUEL: A structured English query language | author = [[Donald D. Chamberlin]] and [[Raymond F. Boyce]] | journal = Proceedings of the 1974 ACM SIGFIDET | pages = 249–264 | year = 1974 }}</ref><ref name="Sim-Diasca">{{cite web | title = Sim-Diasca: a large-scale discrete event concurrent simulation engine in Erlang | url = http://research.edf.com/research-and-the-scientific-community/software/sim-diasca-80704.html |date=November 2011 }}</ref>
<ref name="Spiewak">{{cite web | url = http://www.codecommit.com/blog/scala/implementing-persistent-vectors-in-scala | author = Daniel Spiewak | title = Implementing Persistent Vectors in Scala | accessdate = Apr 17, 2012}}</ref>
<ref name="Opal (programming language)">[[Opal (programming language)|OPtimized Applicative Language]]</ref>
}}
== Further reading ==
* {{cite book|last1=Abelson|first1=Hal|authorlink1=Hal Abelson|last2=Sussman|first2=Gerald Jay|authorlink2=Gerald Jay Sussman | title = Structure and Interpretation of Computer Programs | url = http://mitpress.mit.edu/sicp/ | year = 1985|publisher=MIT Press}}
* Cousineau, Guy and Michel Mauny. ''The Functional Approach to Programming''. Cambridge, UK: [[Cambridge University Press]], 1998.
* Curry, Haskell Brooks and Feys, Robert and Craig, William. ''Combinatory Logic''. Volume I. North-Holland Publishing Company, Amsterdam, 1958.
* {{cite book | last1 = Curry | first1 = Haskell B. | first2 = J. Roger | last2 = Hindley | first3 = Jonathan P. | last3 = Seldin | authorlink1 = Haskell Curry | authorlink2 = J. Roger Hindley | authorlink3 = Jonathan P. Seldin | title = Combinatory Logic | volume = Vol. II | year = 1972 | publisher = North Holland | ___location = Amsterdam | isbn = 0-7204-2208-6 }}
* Dominus, Mark Jason. ''[http://hop.perl.plover.com/book/pdf/HigherOrderPerl.pdf Higher-Order Perl]''. [[Morgan Kaufmann]]. 2005.
* {{cite book|last1=Felleisen|first1=Matthias|last2=Findler|first2=Robert|last3=Flatt|first3=Matthew|first4=Shriram |last4=Krishnamurthi | title = How to Design Programs | url = http://www.htdp.org | year = 2001|publisher=MIT Press}}
* Graham, Paul. ''ANSI Common LISP''. Englewood Cliffs, New Jersey: [[Prentice Hall]], 1996.
* MacLennan, Bruce J. ''Functional Programming: Practice and Theory''. Addison-Wesley, 1990.
* {{cite book|last1=O'Sullivan|first1=Brian|last2=Stewart|first2=Don|last3=Goerzen|first3=John | title = Real World Haskell | url = http://book.realworldhaskell.org/read/ | year = 2008|publisher=O'Reilly}}
* Pratt, Terrence, W. and Marvin V. Zelkowitz. ''Programming Languages: Design and Implementation''. 3rd ed. Englewood Cliffs, New Jersey: [[Prentice Hall]], 1996.
* Salus, Peter H. ''Functional and Logic Programming Languages''. Vol. 4 of Handbook of Programming Languages. Indianapolis, Indiana: [[Macmillan Technical Publishing]], 1998.
* Thompson, Simon. ''Haskell: The Craft of Functional Programming''. Harlow, England: [[Addison-Wesley Longman Limited]], 1996.
== External links ==
{{Spoken Wikipedia|En-Functional_programming.ogg|2011-08-25}}
*{{cite web
| last = Ford
| first = Neal
| title = Functional thinking: Why functional programming is on the rise
| accessdate = 2013-02-24
| date = 2012-01-29
| url = http://www.ibm.com/developerworks/java/library/j-ft20/index.html
}}
* {{cite web
| last = Akhmechet
| first = Slava
| title = defmacro – Functional Programming For The Rest of Us
| accessdate = 2013-02-24
| date = 2006-06-19
| url = http://www.defmacro.org/ramblings/fp.html
}} An introduction
* ''Functional programming in Python'' (by David Mertz): [http://gnosis.cx/publish/programming/charming_python_13.html part 1], [http://gnosis.cx/publish/programming/charming_python_16.html part 2], [http://gnosis.cx/publish/programming/charming_python_19.html part 3]
{{Programming language}}
{{Authority control}}
{{DEFAULTSORT:Functional programming}}
[[Category:Programming paradigms]]
[[Category:Functional programming| ]]' |
Unified diff of changes made by edit (edit_diff ) | '@@ -4,5 +4,7 @@
In [[computer science]], '''functional programming''' is a [[programming paradigm]]—a style of building the structure and elements of [[computer program]]s—that treats [[computation]] as the evaluation of [[function (mathematics)|mathematical function]]s and avoids changing-[[program state|state]] and [[Immutable object|mutable]] data. It is a [[declarative programming]] paradigm, which means programming is done with [[Expression (computer science)|expressions]]<ref name="expression style">{{cite web|url=https://wiki.haskell.org/Declaration_vs._expression_style#Expression_style|title=Declaration vs. expression style - HaskellWiki|publisher=}}</ref> or declarations<ref name="declaration style">{{cite web|url=https://wiki.haskell.org/Declaration_vs._expression_style#Declaration_style|title=Declaration vs. expression style - HaskellWiki|publisher=}}</ref> instead of [[statement (computer science)|statements]]. In functional code, the output value of a function depends only on the [[function argument|argument]]s that are input to the function, so calling a function ''f'' twice with the same value for an argument ''x'' will produce the same result ''f(x)'' each time. Eliminating [[side effect (computer science)|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.
-Functional programming has its origins in [[lambda calculus]], a [[formal system]] developed in the 1930s to investigate [[computability]], the [[Entscheidungsproblem]], function definition, [[function application]], and [[recursion]]. Many functional [[programming language]]s can be viewed as elaborations on the lambda calculus. Another well-known declarative programming paradigm, ''[[logic programming]]'', is based on [[Relation (logic)|relations]].<ref name="hudak1989"/>
+Functional programming has its origins in [[lambda calculus]], a [[formal system]] developed in the 1930s to investigate [[computability]], the [[Entscheidungsproblem]], function definition, [[function applkmllllllllllllllll
+
+ication]], and [[recursion]]. Many functional [[programming language]]s can be viewed as elaborations on the lambda calculus. Another well-known declarative programming paradigm, ''[[logic programming]]'', is based on [[Relation (logic)|relations]].<ref name="hudak1989"/>
In contrast, [[imperative programming]] changes state with commands in the [[source code]], the simplest example being [[assignment (computer science)|assignment]]. Imperative programming does have functions—not in the mathematical sense—but in the sense of [[subroutine]]s. They can have [[side effect (computer science)|side effects]] that may change the value of program state. Functions without [[return value]]s therefore make sense. Because of this, they lack [[referential transparency (computer science)|referential transparency]], i.e. the same language expression can result in different values at different times depending on the state of the executing program.<ref name="hudak1989">{{cite journal | last = Hudak | first = Paul | authorlink = Paul Hudak | title = Conception, evolution, and application of functional programming languages | journal = [[Association for Computing Machinery|ACM]] Computing Surveys|volume=21|issue=3 | pages = 359–411 |date=September 1989 | url = http://www.dbnet.ece.ntua.gr/~adamo/languages/books/p359-hudak.pdf|format=PDF|doi=10.1145/72551.72554 }}</ref>
' |
New page size (new_size ) | 65623 |
Old page size (old_size ) | 65603 |
Size change in edit (edit_delta ) | 20 |
Lines added in edit (added_lines ) | [
0 => 'Functional programming has its origins in [[lambda calculus]], a [[formal system]] developed in the 1930s to investigate [[computability]], the [[Entscheidungsproblem]], function definition, [[function applkmllllllllllllllll',
1 => false,
2 => 'ication]], and [[recursion]]. Many functional [[programming language]]s can be viewed as elaborations on the lambda calculus. Another well-known declarative programming paradigm, ''[[logic programming]]'', is based on [[Relation (logic)|relations]].<ref name="hudak1989"/>'
] |
Lines removed in edit (removed_lines ) | [
0 => 'Functional programming has its origins in [[lambda calculus]], a [[formal system]] developed in the 1930s to investigate [[computability]], the [[Entscheidungsproblem]], function definition, [[function application]], and [[recursion]]. Many functional [[programming language]]s can be viewed as elaborations on the lambda calculus. Another well-known declarative programming paradigm, ''[[logic programming]]'', is based on [[Relation (logic)|relations]].<ref name="hudak1989"/>'
] |
New page wikitext, pre-save transformed (new_pst ) | '{{for|subroutine-oriented programming|Procedural programming}}
{{Programming paradigms}}
In [[computer science]], '''functional programming''' is a [[programming paradigm]]—a style of building the structure and elements of [[computer program]]s—that treats [[computation]] as the evaluation of [[function (mathematics)|mathematical function]]s and avoids changing-[[program state|state]] and [[Immutable object|mutable]] data. It is a [[declarative programming]] paradigm, which means programming is done with [[Expression (computer science)|expressions]]<ref name="expression style">{{cite web|url=https://wiki.haskell.org/Declaration_vs._expression_style#Expression_style|title=Declaration vs. expression style - HaskellWiki|publisher=}}</ref> or declarations<ref name="declaration style">{{cite web|url=https://wiki.haskell.org/Declaration_vs._expression_style#Declaration_style|title=Declaration vs. expression style - HaskellWiki|publisher=}}</ref> instead of [[statement (computer science)|statements]]. In functional code, the output value of a function depends only on the [[function argument|argument]]s that are input to the function, so calling a function ''f'' twice with the same value for an argument ''x'' will produce the same result ''f(x)'' each time. Eliminating [[side effect (computer science)|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.
Functional programming has its origins in [[lambda calculus]], a [[formal system]] developed in the 1930s to investigate [[computability]], the [[Entscheidungsproblem]], function definition, [[function applkmllllllllllllllll
ication]], and [[recursion]]. Many functional [[programming language]]s can be viewed as elaborations on the lambda calculus. Another well-known declarative programming paradigm, ''[[logic programming]]'', is based on [[Relation (logic)|relations]].<ref name="hudak1989"/>
In contrast, [[imperative programming]] changes state with commands in the [[source code]], the simplest example being [[assignment (computer science)|assignment]]. Imperative programming does have functions—not in the mathematical sense—but in the sense of [[subroutine]]s. They can have [[side effect (computer science)|side effects]] that may change the value of program state. Functions without [[return value]]s therefore make sense. Because of this, they lack [[referential transparency (computer science)|referential transparency]], i.e. the same language expression can result in different values at different times depending on the state of the executing program.<ref name="hudak1989">{{cite journal | last = Hudak | first = Paul | authorlink = Paul Hudak | title = Conception, evolution, and application of functional programming languages | journal = [[Association for Computing Machinery|ACM]] Computing Surveys|volume=21|issue=3 | pages = 359–411 |date=September 1989 | url = http://www.dbnet.ece.ntua.gr/~adamo/languages/books/p359-hudak.pdf|format=PDF|doi=10.1145/72551.72554 }}</ref>
Functional programming languages have largely been emphasized in [[academic|academia]] rather than in commercial software development. However, prominent programming languages which support functional programming such as [[Common Lisp]], [[Scheme (programming language)|Scheme]],<ref name="clinger1987"/><ref name="hartheimer1987"/><ref name="kidd2007"/><ref name="cleis2006"/> [[Clojure]],<ref name="useR"/><ref name="Chambers"/> [[Wolfram Language]]<ref name="reference.wolfram.com">{{cite web | title = Wolfram Language Guide: Functional Programming | url = http://reference.wolfram.com/language/guide/FunctionalProgramming.html | year = 2015 | accessdate = 2015-08-24 }}</ref> (also known as [[Mathematica]]), [[Racket (programming language)|Racket]],<ref name="racket-video-games"/> [[Erlang (programming language)|Erlang]],<ref name="erlang-faq"/><ref name="armstrong2007"/><ref name="larson2009"/> [[OCaml]],<ref name="minksy2008"/><ref name="leroy2007"/> [[Haskell (programming language)|Haskell]],<ref name="haskell-industry"/><ref name="hudak2007"/> and [[F Sharp (programming language)|F#]]<ref name='quantFSharp'>{{cite conference | last = Mansell | first = Howard | title = Quantitative Finance in F# | url = http://cufp.galois.com/2008/abstracts.html#MansellHoward | year = 2008 | conference = CUFP 2008 | accessdate = 2009-08-29 }}</ref><ref name='businessAppsFSharp'>{{cite conference | last = Peake | first = Alex | title = The First Substantial Line of Business Application in F# | url = http://cufp.galois.com/2009/abstracts.html#AlexPeakeAdamGranicz | year = 2009 | conference = CUFP 2009 | accessdate = 2009-08-29 }}</ref> have been used in industrial and commercial applications by a wide variety of organizations. Functional programming is also supported in some [[___domain-specific programming language]]s like [[R (programming language)|R]] (statistics),<ref name="Amath-CO"/> [[J (programming language)|J]], [[K (programming language)|K]] and [[Q (programming language from Kx Systems)|Q from Kx Systems]] (financial analysis), [[XQuery]]/[[XSLT]] ([[XML]]),<ref name="Novatchev"/><ref name="Mertz"/> and Opal.<ref name="Opal (programming language)"/> Widespread ___domain-specific declarative languages like [[SQL]] and [[Lex (software)|Lex]]/[[Yacc]] use some elements of functional programming, especially in eschewing [[mutable object|mutable value]]s.<ref name="Chamberlin_Boyce"/>
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.<ref>{{cite book | last = Dominus | first = Mark J. | authorlink = Mark Jason Dominus | title = [[Higher-Order Perl]] |publisher=[[Morgan Kaufmann]] | year = 2005 |isbn = 1-55860-701-3 }}</ref> This is also true of the [[PHP]] programming language.<ref>{{cite book | last = Holywell | first = Simon | title = Functional Programming in PHP | publisher = php[architect] | year = 2014 | isbn = 9781940111056}}</ref> [[C++11]], [[Java programming|Java]] 8, and [[C Sharp (programming language)|C#]] 3.0 all added constructs to facilitate the functional style. The [[Julia (programming language)|Julia]] language also offers functional programming abilities. An interesting case is that of [[Scala (programming language)|Scala]]<ref name="effective-scala"/> – 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.
== History ==
[[Lambda calculus]] provides a theoretical framework for describing functions and their evaluation. Although it is a mathematical abstraction rather than a programming language, it forms the basis of almost all functional programming languages today. 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]].<ref>{{cite book|author1=Haskell Brooks Curry|author2=Robert Feys|title=Combinatory Logic|url=https://books.google.com/books?id=fEnuAAAAMAAJ|accessdate=10 February 2013|year=1958|publisher=North-Holland Publishing Company}}</ref>
An early functional-flavored language was [[Lisp (programming language)|Lisp]], developed in the late 1950s for the [[IBM 700/7000 series#Scientific Architecture|IBM 700/7000 series]] scientific computers by [[John McCarthy (computer scientist)|John McCarthy]] while at [[Massachusetts Institute of Technology]] (MIT).<ref>{{cite journal | first = John | last = McCarthy | authorlink = John McCarthy (computer scientist) | title = History of Lisp | journal = In [[Association for Computing Machinery|ACM]]/SIGPLAN History of Programming Languages Conference | pages = 217–223 |date=June 1978 | url = http://citeseer.ist.psu.edu/mccarthy78history.html|doi=10.1145/800025.808387 }}</ref> Lisp first introduced many paradigmatic features of functional programming, though early Lisps were [[Programming_paradigm#Multi-paradigm|multi-paradigm language]]s, and incorporated support for numerous programming styles as new paradigms evolved. Later dialects, such as [[Scheme (programming language)|Scheme]] and [[Clojure]], and offshoots such as [[Dylan (programming language)|Dylan]] and [[Julia (programming language)|Julia]], sought to simplify and rationalise Lisp around a cleanly functional core, while [[Common Lisp]] was designed to preserve and update the paradigmatic features of the numerous older dialects it replaced.<ref>{{cite journal|author1=Guy L. Steele |author2=Richard P. Gabriel |title=The Evolution of Lisp |journal= In [[Association for Computing Machinery|ACM]]/SIGPLAN Second History of Programming Languages |pages= 233-330 |date=February 1996 |url=http://dreamsongs.com/Files/HOPL2-Uncut.pdf |doi= 10.1145/234286.1057818 }}</ref>
[[Information Processing Language]] (IPL) is sometimes cited as the first computer-based functional programming language.<ref>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 which proved theorems from ''[[Principia Mathematica]]'' automatically. In order to accomplish this, they had to invent a language and a paradigm which, which viewed retrospectively, embeds functional programming.</ref> It is an [[assembly language|assembly-style language]] for manipulating lists of symbols. It does have a notion of "generator", which amounts to a function accepting a function as an argument, and, since it is an assembly-level language, code can be used as data, so IPL can be regarded as having higher-order functions. However, it relies heavily on mutating list structure and similar imperative features.
[[Kenneth E. Iverson]] developed [[APL (programming language)|APL]] in the early 1960s, described in his 1962 book ''A Programming Language'' (ISBN 9780471430148). APL was the primary influence on [[John Backus]]'s [[FP (programming language)|FP]]. In the early 1990s, Iverson and [[Roger Hui]] created [[J (programming language)|J]]. In the mid-1990s, [[Arthur Whitney (computer scientist)|Arthur Whitney]], who had previously worked with Iverson, created [[K (programming language)|K]], which is used commercially in financial industries along with its descendant [[Q (programming language from Kx Systems)|Q]].
[[John Backus]] presented [[FP (programming language)|FP]] in his 1977 [[Turing Award]] lecture "Can Programming Be Liberated From the [[Von Neumann architecture|von Neumann]] Style? A Functional Style and its Algebra of Programs".<ref>{{cite web|url=http://worrydream.com/refs/Backus-CanProgrammingBeLiberated.pdf|title=Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs|format=PDF}}</ref> He defines functional programs as being built up in a hierarchical way by means of "combining forms" that allow an "algebra of programs"; in modern language, this means that functional programs follow the [[principle of compositionality]]{{Citation needed|reason=I dont completely agree with this interpretation of John Backus definition of functional programs, which I feel is widely misunderstood. As he is very sadly no longer alive we can't ask him, but a reference for this interpretation, especially if it includes a justification, would be very beneficial.|date=February 2017}}. Backus's paper popularized research into functional programming, though it emphasized [[function-level programming]] rather than the lambda-calculus style which has come to be associated with functional programming.
In the 1970s, [[ML (programming language)|ML]] was created by [[Robin Milner]] at the [[University of Edinburgh]], and [[David Turner (computer scientist)|David Turner]] initially developed the language [[SASL (programming language)|SASL]] at the [[University of St Andrews]] and later the language [[Miranda (programming language)|Miranda]] at the [[University of Kent]]. Also in Edinburgh in the 1970s, Burstall and Darlington developed the functional language [[NPL (programming language)|NPL]].<ref>R.M. Burstall. Design considerations for a functional programming language. Invited paper, Proc. Infotech State of the Art Conf. "The Software Revolution", Copenhagen, 45–57 (1977)</ref> NPL was based on [[Kleene's recursion theorem|Kleene Recursion Equations]] and was first introduced in their work on program transformation.<ref>R.M. Burstall and J. Darlington. A transformation system for developing recursive programs. Journal of the Association for Computing Machinery 24(1):44–67 (1977)</ref> Burstall, MacQueen and Sannella then incorporated the polymorphic type checking from ML to produce the language [[Hope (programming language)|Hope]].<ref>R.M. Burstall, D.B. MacQueen and D.T. Sannella. HOPE: an experimental applicative language. Proc. 1980 LISP Conference, Stanford, 136–143 (1980).</ref> ML eventually developed into several dialects, the most common of which are now [[OCaml]] and [[Standard ML]]. Meanwhile, the development of [[Scheme (programming language)|Scheme]], a simple [[lexical scope|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.
In the 1980s, [[Per Martin-Löf]] developed [[intuitionistic type theory]] (also called ''constructive'' type theory), which associated functional programs with [[constructive proof]]s of arbitrarily complex mathematical propositions expressed as [[dependent type]]s. This led to powerful new approaches to [[interactive theorem proving]] and has influenced the development of many subsequent functional programming languages.
The [[Haskell (programming language)|Haskell language]] began with a consensus in 1987 to form an [[open standard]] for functional programming research; implementation releases have been ongoing since 1990.
== Concepts ==
A number of concepts and paradigms are specific to functional programming, and generally foreign to [[imperative programming]] (including [[object-oriented programming]]). However, programming languages are often hybrids of several programming paradigms, so programmers using "mostly imperative" languages may have utilized some of these concepts.<ref>{{cite web | url = http://byte.com/art/9408/sec11/art1.htm | archiveurl = https://web.archive.org/web/20060827094123/http://byte.com/art/9408/sec11/art1.htm | archivedate = 2006-08-27 | title = Functional Programming Comes of Age | author = Dick Pountain | work=BYTE.com (August 1994) | accessdate = August 31, 2006 }}</ref>
=== First-class and higher-order functions ===
{{main article|First-class function|Higher-order function}}
[[Higher-order function]]s are functions that can either take other functions as arguments or return them as results. In calculus, an example of a higher-order function is the [[differential operator]] <math>d/dx</math>, which returns the [[derivative]] of a function <math>f</math>.
Higher-order functions are closely related to [[first-class function]]s in that higher-order functions and first-class functions both allow functions as arguments and results of other functions. The distinction between the two is subtle: "higher-order" describes a mathematical concept of functions that operate on other functions, while "first-class" is a computer science term that describes programming language entities that have no restriction on their use (thus first-class functions can appear anywhere in the program that other first-class entities like numbers can, including as arguments to other functions and as their return values).
Higher-order functions enable [[partial application]] or [[currying]], a technique in which a function is applied to its arguments one at a time, with each application returning a new function that accepts the next argument. This allows one to succinctly express, for example, the [[successor function]] as the addition operator partially applied to the [[natural number]] one.
=== Pure functions ===
[[Pure function]]s (or expressions) have no [[side effect (computer science)|side effects]] (memory or I/O). This means that pure functions have several useful properties, many of which can be used to optimize the code:
* If the result of a pure expression is not used, it can be removed without affecting other expressions.
* 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 (computer science)|referential transparency]]), i.e. if the pure function is again called with the same arguments, the same result will be returned (this can enable caching optimizations such as [[memoization]]).
* If there is no data dependency between two pure expressions, then their order can be reversed, or they can be performed in [[parallelization|parallel]] and they cannot interfere with one another (in other terms, the evaluation of any pure expression is [[thread-safe]]).
* If the entire language does not allow side-effects, then any evaluation strategy can be used; this gives the compiler freedom to reorder or combine the evaluation of expressions in a program (for example, using [[deforestation (computer science)|deforestation]]).
While most compilers for imperative programming languages detect pure functions and perform common-subexpression elimination for pure function calls, they cannot always do this for pre-compiled libraries, which generally do not expose this information, thus preventing optimizations that involve those external functions. Some compilers, such as [[GNU Compiler Collection|gcc]], add extra keywords for a programmer to explicitly mark external functions as pure, to enable such optimizations. [[Fortran 95]] also allows functions to be designated "pure".
=== Recursion ===
{{Main article|Recursion (computer science)}}
[[Iteration]] (looping) in functional languages is usually accomplished via [[recursion]]. [[recursion (computer science)|Recursive function]]s invoke themselves, allowing an operation to be performed over and over until the [[Recursion (computer science)|base case]] is reached. 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 (programming language)|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.
Common patterns of recursion can be factored out using higher order functions, with [[catamorphism]]s and [[anamorphism]]s (or "folds" and "unfolds") being the most obvious examples. Such higher order functions play a role analogous to built-in control structures such as [[Program loops|loops]] in [[imperative languages]].
Most general purpose functional programming languages allow unrestricted recursion and are [[Turing complete]], which makes the [[halting problem]] [[undecidable problem|undecidable]], can cause unsoundness of [[equational reasoning]], and generally requires the introduction of [[inconsistency]] into the logic expressed by the language's [[type system]]. Some special purpose languages such as [[Coq]] allow only [[well-founded]] recursion and are [[strongly normalizing]] (nonterminating computations can be expressed only with infinite streams of values called [[codata (computer science)|codata]]). As a consequence, these languages fail to be Turing complete and expressing certain functions in them is impossible, but they can still express a wide class of interesting computations while avoiding the problems introduced by unrestricted recursion. Functional programming limited to well-founded recursion with a few other constraints is called [[total functional programming]].<ref name=totalfp>{{cite journal | last = Turner | first = D.A.|author-link=David Turner (computer scientist) | title = Total Functional Programming | journal = Journal of Universal Computer Science|volume=10| date = 2004-07-28 | pages = 751–768 | url = http://www.jucs.org/jucs_10_7/total_functional_programming|doi=10.3217/jucs-010-07-0751|issue=7}}</ref>
=== Strict versus non-strict evaluation ===
{{Main article|Evaluation strategy}}
Functional languages can be categorized by whether they use ''strict (eager)'' or ''non-strict (lazy)'' evaluation, concepts that refer to how function arguments are processed when an expression is being evaluated. The technical difference is in the [[denotational semantics]] of expressions containing failing or divergent computations. Under strict evaluation, the evaluation of any term containing a failing subterm will itself fail. For example, the expression:
<!-- language? -->
print length([2+1, 3*2, 1/0, 5-4])
will fail under strict evaluation because of the division by zero in the third element of the list. Under lazy evaluation, the length function will return the value 4 (i.e., the number of items in the list), since evaluating it will 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]].<ref>[http://research.microsoft.com/~simonpj/papers/slpj-book-1987/index.htm The Implementation of Functional Programming Languages]. Simon Peyton Jones, published by Prentice Hall, 1987</ref> Lazy evaluation is used by default in several pure functional languages, including [[Miranda (programming language)|Miranda]], [[Clean (programming language)|Clean]], and [[Haskell (programming language)|Haskell]].
{{Harvnb|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.<ref>{{cite web |url=http://www.cse.chalmers.se/~rjmh/Papers/whyfp.html |title=Why Functional Programming Matters |authorlink=John Hughes (computer scientist) |first=John |last=Hughes |year=1984 |ref=harv}}</ref> Launchbury 1993 <!-- a cite arguing more strongly against lazy evaluation would be preferable here, if someone knows of one. --> 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.<ref name=launchbury1993>{{cite web | url = http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.35.2016 | author = John Launchbury | title = A Natural Semantics for Lazy Evaluation | year = 1993 }}</ref> Harper 2009 proposes including both strict and lazy evaluation in the same language, using the language's type system to distinguish them.<ref>{{cite book | url = http://www.cs.cmu.edu/~rwh/plbook/book.pdf | title = Practical Foundations for Programming Languages | author = Robert W. Harper | authorlink=Robert_Harper_(computer_scientist) | year = 2009 }}</ref>
=== Type systems ===
<!-- expand this section!!! also split it into several sections -->
Especially since the development of [[Hindley–Milner type inference]] in the 1970s, functional programming languages have tended to use [[typed lambda calculus]], rejecting all invalid programs at compilation time and risking [[false positives and false negatives#False positive error|false positive errors]], as opposed to the [[untyped lambda calculus]], that accepts all valid programs at compilation time and risks [[false positives and false negatives#False negative error|false negative errors]], used in Lisp and its variants (such as [[Scheme (programming language)|Scheme]]), although they reject all invalid programs at runtime, when the information is enough to not reject valid programs. The use of [[algebraic datatypes]] makes manipulation of complex data structures convenient; the presence of strong compile-time type checking makes programs more reliable in absence of other reliability techniques like [[test-driven development]], while [[type inference]] frees the programmer from the need to manually declare types to the compiler in most cases.
Some research-oriented functional languages such as [[Coq]], [[Agda (theorem prover)|Agda]], [[Cayenne (programming language)|Cayenne]], and [[Epigram (programming language)|Epigram]] are based on [[intuitionistic type theory]], which allows types to depend on terms. Such types are called [[dependent type]]s. These type systems do not have decidable type inference and are difficult to understand and program with{{Citation needed| date = December 2011}}. But dependent types can express arbitrary propositions in [[predicate logic]]. Through the [[Curry–Howard isomorphism]], then, well-typed programs in these languages become a means of writing formal [[mathematical proof]]s from which a compiler can generate [[formal verification|certified code]]. While these languages are mainly of interest in academic research (including in [[formalized mathematics]]), they have begun to be used in engineering as well. [[Compcert]] is a [[compiler]] for a subset of the [[C (programming language)|C programming language]] that is written in Coq and formally verified.<ref>{{cite web | url = http://compcert.inria.fr/doc/index.html | title = The Compcert verified compiler }}</ref>
A limited form of dependent types called [[generalized algebraic data type]]s (GADT's) can be implemented in a way that provides some of the benefits of dependently typed programming while avoiding most of its inconvenience.<ref>{{cite web | url = http://research.microsoft.com/en-us/um/people/simonpj/papers/gadt/ | title = Simple unification-based type inference for GADTs |author1=Simon Peyton Jones |author2=Dimitrios Vytiniotis |author3=Stephanie Weirich |author4=Geoffrey Washburn | work=ICFP 2006 | pages = 50–61 }}</ref> GADT's are available in the [[Glasgow Haskell Compiler]], in [[OCaml]] (since version 4.00) and in [[Scala (programming language)|Scala]] (as "case classes"), and have been proposed as additions to other languages including Java and C#.<ref>{{cite web | title = Generalized Algebraic Data Types and Object-Oriented Programming |author1=Andrew Kennedy |author2=Claudio Russo | work=OOPSLA | date = October 2005 | ___location = San Diego, California | url = http://research.microsoft.com/~akenn/generics/gadtoop.pdf | archiveurl = https://web.archive.org/web/20061229164852/http://research.microsoft.com/~akenn/generics/gadtoop.pdf | archivedate = 2006-12-29 }} [http://lambda-the-ultimate.org/node/1134 source of citation]</ref>
=== Referential transparency ===
{{Main article|Referential transparency}}
Functional programs do not have assignment statements, that is, the value of a variable in a functional program never changes once defined. This eliminates any chances of side effects because any variable can be replaced with its actual value at any point of execution. So, functional programs are referentially transparent.<ref>{{cite web|last1=Huges|first1=John|title=Why Functional Programming Matters|url=http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf|website=http://www.chalmers.se/cse|publisher=Chalmers Tekniska H¨ogskola}}</ref>
Consider [[C (programming language)|C]] assignment statement <code>x = x * 10</code>, this changes the value assigned to the variable <code>x</code>. Let us say that the initial value of <code>x</code> was <code>1</code>, then two consecutive evaluations of the variable <code>x</code> will yield <code>10</code> and <code>100</code> respectively. Clearly, replacing <code>x = x * 10</code> with either <code>10</code> or <code>100</code> gives a program with different meaning, and so the expression ''is not'' referentially transparent. In fact, assignment statements are never referentially transparent.
Now, consider another function such as <code>int plusone(int x) {return x+1;}</code> ''is'' transparent, as it will not implicitly change the input x and thus has no such [[side effect (computer science)|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.<ref>{{cite journal | last = Hartel | first = Pieter |author2=Henk Muller |author3=Hugh Glaser | title = The Functional C experience | journal = Journal of Functional Programming | volume=14 |issue=2 | pages = 129–135 |date=March 2004 | url = http://www.ub.utwente.nl/webdocs/ctit/1/00000084.pdf |format=PDF| doi=10.1017/S0956796803004817}}; {{cite web | title = Functional programming in Python, Part 3 | url = http://www-128.ibm.com/developerworks/linux/library/l-prog3.html | archiveurl = http://wayback.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog3.html | archivedate = 2007-10-16 | author = David Mertz | accessdate = 2006-09-17 | work=IBM developerWorks}}([http://wayback.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog.html Part 1], [http://wayback.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog2.html Part 2])</ref> For example, both [[D (programming language)|D]] and [[Fortran 95]] explicitly support pure functions.<ref>{{cite web | url = http://www.digitalmars.com/d/2.0/function.html#pure-functions | title = Functions — D Programming Language 2.0 |publisher=Digital Mars | accessdate = 2011-06-20 }}</ref>
[[JavaScript]], [[Lua (programming language)|Lua]]<ref>{{cite web|url=http://www.luafaq.org/#T1.2|title=Lua Unofficial FAQ (uFAQ)|publisher=}}</ref> and [[Python (programming language)|Python]] had [[First-class function|first class functions]] from their inception.<ref>{{cite web|url=https://brendaneich.com/2008/04/popularity/|title=Brendan Eich|publisher=}}</ref> Amrit Prem added support to Python for "[[anonymous function|lambda]]", "[[Map (higher-order function)|map]]", "[[Fold (higher-order function)|reduce]]", and "[[Filter (higher-order function)|filter]]" in 1994, as well as closures in Python 2.2,<ref>{{cite web |url=http://python-history.blogspot.de/2009/04/origins-of-pythons-functional-features.html |title=Origins of Python's "Functional" Features |last=van Rossum |first=Guido |authorlink=Guido van Rossum |publisher=[http://python-history.blogspot.de/ The History of Python] |date=2009-04-21 |accessdate=2012-09-27 }}</ref> though Python 3 relegated "reduce" to the <code>functools</code> standard library module.<ref>{{cite web | url = https://docs.python.org/dev/library/functools.html#functools.reduce | title = functools — Higher order functions and operations on callable objects | publisher=Python Software Foundation | date = 2011-07-31 | accessdate = 2011-07-31}}</ref> First-class functions have been introduced into other mainstream languages such as [[PHP]] 5.3, [[Visual Basic]] 9, [[C Sharp (programming language)|C#]] 3.0, and [[C++11]].{{citation needed|date=April 2015}}
In [[Java (programming language)|Java]], [[anonymous class]]es can sometimes be used to simulate [[Closure (computer science)|closure]]s;<ref>{{cite book | last = Skarsaune | first = Martin | title = The SICS Java Port Project Automatic Translation of a Large Object Oriented System from Smalltalk to Java | year = 2008 }}</ref> however, anonymous classes are not always proper replacements to [[Closure (computer science)|closure]]s because they have more limited capabilities.<ref>{{cite web|last=Gosling|first=James|title=Closures|url=http://blogs.oracle.com/jag/entry/closures|work=James Gosling: on the Java Road|publisher=Oracle|accessdate=11 May 2013}}</ref> Java 8 supports lambda expressions as a replacement for some anonymous classes.<ref>{{cite web|url=https://blogs.oracle.com/javatraining/entry/java_se_8_lambda_quick|title=Java SE 8 Lambda Quick Start}}</ref> 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|date=March 2014}}
In [[C Sharp (programming language)|C#]], [[anonymous class]]es are not necessary, because [[Closure (computer science)|closure]]s and lambdas are fully supported. Libraries and language extensions for immutable data structures are being developed to aid programming in the functional style in C#.
Many [[object-oriented]] [[Design pattern (computer science)|design pattern]]s are expressible in functional programming terms: for example, the [[strategy pattern]] simply dictates use of a higher-order function, and the [[visitor (design pattern)|visitor]] pattern roughly corresponds to a [[catamorphism]], or [[fold (higher-order function)|fold]].
Similarly, the idea of immutable data from functional programming is often included in imperative programming languages,<ref>{{cite book | title = Effective Java | edition = Second | first = Joshua | last = Bloch | pages = Item 15 }}</ref> for example the tuple in Python, which is an immutable array.
===Data structures===
{{main article|Purely functional data structure}}
Purely functional [[data structure]]s are often represented in a different way than their [[imperative programming|imperative]] counterparts.<ref>[http://www.cambridge.org/us/academic/subjects/computer-science/algorithmics-complexity-computer-algebra-and-computational-g/purely-functional-data-structures ''Purely functional data structures''] by [[Chris Okasaki]], [[Cambridge University Press]], 1998, ISBN 0-521-66350-4</ref> For example, [[array data structure|array]] with constant-time access and update is a basic component of most imperative languages and many imperative data-structure, such as [[hash table]] and [[binary heap]], are based on arrays. Arrays can be replaced by [[Map (computer science)|map]] or [[random access list]], which admits purely functional implementation, but the access and update time is [[logarithm]]ic. Therefore, purely functional data structures can be used in languages which are non-functional, but they may not be the most efficient tool available, especially if persistency is not required.
== Comparison to imperative programming ==
Functional programming is very different from [[imperative programming]]. The most significant differences stem from the fact that functional programming avoids [[side effect (computer science)|side effects]], which are used in imperative programming to implement state and I/O. Pure functional programming completely prevents side-effects and provides [[referential transparency (computer science)|referential transparency]].
Higher-order functions are rarely used in older imperative programming. A traditional imperative program might use a loop to traverse and modify a list. A functional program, on the other hand, would probably use a higher-order “map” function that takes a function and a list, generating and returning a new list by applying the function to each list item.
=== Simulating state ===
There are tasks (for example, maintaining a bank account balance) that often seem most naturally implemented with state. Pure functional programming performs these tasks, and I/O tasks such as accepting user input and printing to the screen, in a different way.
The pure functional programming language [[Haskell (programming language)|Haskell]] implements them using [[monad (functional programming)|monads]], derived from [[category theory]]. Monads offer a way to abstract certain types of computational patterns, including (but not limited to) modeling of computations with mutable state (and other side effects such as I/O) in an imperative manner without losing purity. While existing monads may be easy to apply in a program, given appropriate templates and examples, many students find them difficult to understand conceptually, e.g., when asked to define new monads (which is sometimes needed for certain types of libraries).<ref>{{cite web | last = Newbern | first = J. | title = All About Monads: A comprehensive guide to the theory and practice of monadic programming in Haskell | url = http://monads.haskell.cz/html/index.html/html/ | accessdate = 2008-02-14 }}</ref>
Another way in which functional languages can simulate state is by passing around a [[data structure]] that represents the current state as a parameter to function calls. On each function call, a copy of this data structure is created with whatever differences are the result of the function. This is referred to as '[[state-passing style]]'.
<!-- TO DO: Expand -->
Impure functional languages usually include a more direct method of managing mutable state. [[Clojure]], for example, uses managed references that can be updated by applying pure functions to the current state. This kind of approach enables mutability while still promoting the use of pure functions as the preferred way to express computations.
<!-- TO DO: Expand / example code?? -->
Alternative methods such as [[Hoare logic]] and [[uniqueness type|uniqueness]] have been developed to track side effects in programs. Some modern research languages use [[effect system]]s to make the presence of side effects explicit.
<!-- TO DO: Expand -->
=== Efficiency issues ===
Functional programming languages are typically less efficient in their use of [[central processing unit|CPU]] and memory than imperative languages such as [[C (programming language)|C]] and [[Pascal (programming language)|Pascal]].<ref>{{cite book|author=Larry C. Paulson|title=ML for the Working Programmer|url=https://books.google.com/books?id=XppZdaDs7e0C|accessdate=10 February 2013|date=28 June 1996|publisher=Cambridge University Press|isbn=978-0-521-56543-1}}</ref> <!-- Paulson mentions the reputation for inefficiency in Sec. 1.5; perhaps a more in-depth discussion could be found. --> 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. <!-- perhaps this could be formulated by someone who knows the subject, I was simply curious about unexplained statement "logarithmic slowdown" --> 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).<ref name="Spiewak"/> However, such slowdowns are not universal. For programs that perform intensive numerical computations, functional languages such as [[OCaml]] and [[Clean (programming language)|Clean]] are only slightly slower than C.<ref>{{cite web | url = http://benchmarksgame.alioth.debian.org/u32/which-programs-are-fastest.php?gcc=on&ghc=on&clean=on&ocaml=on&sbcl=on&fsharp=on&racket=on&clojure=on&hipe=on&calc=chart | title = Which programs are fastest? | Computer Language Benchmarks Game | publisher=benchmarksgame.alioth.debian.org | accessdate = 2011-06-20 }}</ref> For programs that handle large [[matrix (mathematics)|matrices]] and multidimensional [[database]]s, [[array programming|array]] functional languages (such as [[J (programming language)|J]] and [[K (programming language)|K]]) were designed with speed optimizations.
Immutability of data can in many cases lead to execution efficiency by allowing the compiler to make assumptions that are unsafe in an imperative language, thus increasing opportunities for [[inline expansion]].<ref>{{cite journal | title = Immutability specification and its applications |author1=Igor Pechtchanski |author2=Vivek Sarkar | journal = Concurrency and Computation: Practice and Experience | volume = 17 | issue = 5–6 | pages = 639–662 | year = 2005 | doi = 10.1002/cpe.853 }}</ref>
[[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 leak]]s if used improperly). Launchbury 1993<ref name=launchbury1993/> discusses theoretical issues related to memory leaks from lazy evaluation, and O'Sullivan ''et al.'' 2008<ref>{{cite web | url = http://book.realworldhaskell.org/read/profiling-and-optimization.html#x_eK1 | title = Chapter 25. Profiling and optimization |publisher=Book.realworldhaskell.org | accessdate = 2011-06-20 }}</ref> 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|date=June 2014}}.
=== Coding styles ===
{{unreferenced section|date=July 2013}}
Imperative programs have the environment and a sequence of steps manipulating the environment. Functional programs have an expression that is successively substituted until it reaches normal form. An example illustrates this with different solutions to the same programming goal (calculating [[Fibonacci number]]s).
====[[Python (programming language)|Python]]====
Printing first 10 Fibonacci numbers, iterative
<source lang="python">
def fibonacci(n, first=0, second=1):
while n != 0:
print(first, end="\n") # side-effect
n, first, second = n - 1, second, first + second # assignment
fibonacci(10)
</source>
Printing first 10 Fibonacci numbers, functional expression style
<source lang="python">
fibonacci = (lambda n, first=0, second=1:
"" if n == 0 else
str(first) + "\n" + fibonacci(n - 1, second, first + second))
print(fibonacci(10), end="")
</source>
Printing a list with first 10 Fibonacci numbers, with generators
<source lang="python">
def fibonacci(n, first=0, second=1):
while n != 0:
yield first
n, first, second = n - 1, second, first + second # assignment
print(list(fibonacci(10)))
</source>
Printing a list with first 10 Fibonacci numbers, functional expression style
<source lang="python">
fibonacci = (lambda n, first=0, second=1:
[] if n == 0 else
[first] + fibonacci(n - 1, second, first + second))
print(fibonacci(10))
</source>
====[[Haskell (programming language)|Haskell]]====
Printing first 10 Fibonacci numbers, functional expression style<ref name="expression style" />
<source lang="haskell">
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)
</source>
Printing a list with first 10 Fibonacci numbers, functional expression style<ref name="expression style" />
<source lang="haskell">
fibonacci_aux = \n first second->
if n == 0 then [] else
[first] ++ fibonacci_aux (n - 1) second (first + second)
fibonacci = \n-> fibonacci_aux n 0 1
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" />
<source lang="haskell">
fibonacci = \n-> if n == 0 then 0
else if n == 1 then 1
else fibonacci(n - 1) + fibonacci(n - 2)
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style,<ref name="expression style" /> [[tail recursive]]
<source lang="haskell">
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))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" /> with recursive lists
<source lang="haskell">
fibonacci_aux = \first second-> first : fibonacci_aux second (first + second)
select = \n zs-> if n==0 then head zs
else select (n - 1) (tail zs)
fibonacci = \n-> select n (fibonacci_aux 0 1)
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" /> with primitives for recursive lists
<source lang="haskell">
fibonacci_aux = \first second-> first : fibonacci_aux second (first + second)
fibonacci = \n-> (fibonacci_aux 0 1) !! n
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional expression style<ref name="expression style" /> with primitives for recursive lists, more concisely
<source lang="haskell">
fibonacci_aux = 0:1:zipWith (+) fibonacci_aux (tail fibonacci_aux)
fibonacci = \n-> fibonacci_aux !! n
main = putStrLn (show (fibonacci 10))
</source>
Printing the 11th Fibonacci number, functional declaration style,<ref name="declaration style" /> [[tail recursive]]
<source lang="haskell">
fibonacci_aux 0 first _ = first
fibonacci_aux n first second = fibonacci_aux (n - 1) second (first + second)
fibonacci n = fibonacci_aux n 0 1
main = putStrLn (show (fibonacci 10))
</source>Printing the 11th Fibonacci number, functional declaration style, using [[Lazy evaluation|lazy]] [[Lazy evaluation|infinite lists]] and primitives<syntaxhighlight lang="haskell">
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
-- an infinite list of the fibonacci numbers
-- fibs is defined in terms of fibs
fibonacci = (fibs !!)
main = putStrLn $ show $ fibonacci 11
</syntaxhighlight>
====Perl 6====
As influenced by Haskell and others, [[Perl 6]] has several functional and declarative approaches to problems. For example, you can declaratively build up a well-typed recursive version (the type constraints are optional) through signature pattern matching:
<source lang="perl6">
subset NonNegativeInt of Int where * >= 0;
proto fib (|) is cached returns NonNegativeInt {*}
multi fib (0) { 0 }
multi fib (1) { 1 }
multi fib (NonNegativeInt $n) { fib($n - 1) + fib($n - 2) }
for ^10 -> $n { say fib($n) }
</source>
An alternative to this is to construct a lazy iterative sequence, which appears as an almost direct illustration of the sequence:
<source lang="perl6">
my @fib = 0, 1, *+* ... *; # Each additional entry is the sum of the previous two
# and this sequence extends lazily indefinitely
say @fib[^10]; # Display the first 10 entries
</source>
====[[Erlang (programming language)|Erlang]]====
'''[[Erlang (programming language)|Erlang]]''' is a functional, concurrent, general-purpose programming language. A [[Fibonacci number|Fibonacci]] algorithm implemented in Erlang (Note: This is only for demonstrating the Erlang [[Syntax (programming languages)|syntax]]. Use other algorithms for fast performance<ref>[http://www.aquabu.com/2008/02/16/fibonacci-sequence-recursion-in-erlang/]{{dead link|date=February 2016}}</ref>):
<source lang="erlang">
-module(fib). % This is the file 'fib.erl', the module and the filename must match
-export([fib/1]). % This exports the function 'fib' of arity 1
fib(1) -> 1; % If 1, then return 1, otherwise (note the semicolon ; meaning 'else')
fib(2) -> 1; % If 2, then return 1, otherwise
fib(N) -> fib(N - 2) + fib(N - 1).
</source>
==== Elixir ====
'''[[Elixir (programming language)|Elixir]]''' is a functional, concurrent, general-purpose programming language that runs on the [[Erlang (programming language)|Erlang virtual machine (BEAM)]].
The Fibonacci function can be written in Elixir as follows:<syntaxhighlight lang="elixir">
defmodule Fibonacci do
def fib(0), do: 0
def fib(1), do: 1
def fib(n), do: fib(n-1) + fib(n-2)
end
</syntaxhighlight>
====Lisp====
The Fibonacci function can be written in [[Common Lisp]] as follows:
<source lang="lisp">
(defun fib (n &optional (a 0) (b 1))
(if (= n 0)
a
(fib (- n 1) b (+ a b))))
</source>
The program can then be called as
<source lang="lisp">
(fib 10)
</source>
====[[Clojure]]====
The Fibonacci function can be written in [[Clojure]] as follows:
<source lang="clojure">
(defn fib
[n]
(loop [a 0 b 1 i n]
(if (zero? i)
a
(recur b (+ a b) (dec i)))))
</source>
The program can then be called as
<source lang="clojure">
(fib 7)
</source>
====D====
[[D (programming language)|D]] has support for functional programming{{clarify|date=April 2015}}{{citation needed|date=April 2015}}:
<source lang="d">
import std.stdio;
import std.range;
void main()
{
/* 'f' is a range representing the first 10 Fibonacci numbers */
auto f = recurrence!((seq, i) => seq[0] + seq[1])(0, 1)
.take(10);
writeln(f);
}
</source>
====R====
[[R (programming language)|R]] is an environment for statistical computing and graphics. It is also a functional programming language.
The Fibonacci function can be written in [[R (programming language)|R]] as a recursive function as follows:
<source lang="rsplus">
fib <- function(n) {
if (n <= 2) 1
else fib(n - 1) + fib(n - 2)
}
</source>
Or it can be written as a singly recursive function:
<source lang="rsplus">
fib <- function(n,a=1,b=1) {
if (n == 1) a
else fib(n-1,b,a+b)
}
</source>
Or it can be written as an iterative function:
<source lang="rsplus">
fib <- function(n) {
if (n == 1) 1
else if (n == 2) 1
else {
fib<-c(1,1)
for (i in 3:n) fib<-c(0,fib[1])+fib[2]
fib[2]
}
}
</source>
The function can then be called as
<source lang="rsplus">
fib(10)
</source>
====[[SequenceL]]====
SequenceL is a functional, concurrent, general-purpose programming language. The Fibonacci function can be written in SequenceL as follows:
<source lang="haskell">
fib(n) := n when n < 2 else
fib(n - 1) + fib(n - 2);
</source>
The function can then be called as
<source lang="haskell">
fib(10)
</source>
To reduce the memory consumed by the call stack when computing a large Fibonacci term, a tail-recursive version can be used. A tail-recursive function is implemented by the SequenceL compiler as a memory-efficient looping structure:
<source lang="haskell">
fib(n) := fib_Helper(0, 1, n);
fib_Helper(prev, next, n) :=
prev when n < 1 else
next when n = 1 else
fib_Helper(next, next + prev, n - 1);
</source>
== Use in industry ==
Functional programming has long been popular in academia, but with few industrial applications.<ref name='programmingScala'>{{cite book | first1 = Martin | last1 = Odersky | first2 = Lex | last2 = Spoon | first3 = Bill | last3 = Venners | date = December 13, 2010 | title = Programming in Scala: A Comprehensive Step-by-step Guide | publisher = [[Artima Inc]] | edition = 2nd | pages = 883/852 | isbn = 978-0-9815316-4-9 | url = http://www.artima.com/shop/programming_in_scala_2ed }}</ref>{{rp|page 11}} However, recently several prominent functional programming languages have been used in commercial or industrial systems. For example, the [[Erlang (programming language)|Erlang]] programming language, which was developed by the [[Sweden|Swedish]] company [[Ericsson]] in the late 1980s, was originally used to implement fault-tolerant telecommunications systems.<ref name="armstrong2007"/> It has since become popular for building a range of applications at companies such as [[T-Mobile]], [[Nortel]], [[Facebook]], [[Électricité de France]] and [[WhatsApp]].<ref name="erlang-faq"/><ref name="larson2009"/><ref>{{cite conference | last = Piro | first = Christopher | title = Functional Programming at Facebook | url = http://cufp.galois.com/2009/abstracts.html#ChristopherPiroEugeneLetuchy | year = 2009 | conference = CUFP 2009 | accessdate = 2009-08-29 }}</ref><ref name="Sim-Diasca"/><ref name="whatsapp.blog.2012">[http://blog.whatsapp.com/index.php/2012/01/1-million-is-so-2011/ 1 million is so 2011] // WhatsApp blog, 2012-01-06: "the last important piece of our infrastracture is Erlang"</ref> The [[Scheme (programming language)|Scheme]] dialect of [[Lisp (programming language)|Lisp]] was used as the basis for several applications on early [[Apple Macintosh]] computers,<ref name="clinger1987"/><ref name="hartheimer1987"/> and has more recently been applied to problems such as training [[Computer simulation|simulation software]]<ref name="kidd2007"/> and [[telescope]] control.<ref name="cleis2006"/> [[OCaml]], which was introduced in the mid-1990s, has seen commercial use in areas such as financial analysis,<ref name="minksy2008"/> [[software driver|driver]] verification, industrial [[robot]] programming, and static analysis of [[embedded software]].<ref name="leroy2007"/> [[Haskell (programming language)|Haskell]], although initially intended as a research language,<ref name="hudak2007"/> has also been applied by a range of companies, in areas such as aerospace systems, hardware design, and web programming.<ref name="haskell-industry"/><ref name="hudak2007"/>
Other functional programming languages that have seen use in industry include [[Scala (programming language)|Scala]],<ref>{{cite conference | last = Momtahan | first = Lee | title = Scala at EDF Trading: Implementing a Domain-Specific Language for Derivative Pricing with Scala | url = http://cufp.galois.com/2009/abstracts.html#LeeMomtahan | year = 2009 | conference = CUFP 2009 | accessdate = 2009-08-29 }}</ref> [[F Sharp (programming language)|F#]],<ref name='quantFSharp'/><ref name='businessAppsFSharp'/> (both being functional-OO hybrids with support for both purely functional and imperative programming) [[Wolfram Language]],<ref name="reference.wolfram.com"/> [[Lisp (programming language)|Lisp]],<ref>{{cite web | last = Graham | first = Paul | title = Beating the Averages | url = http://www.paulgraham.com/avg.html | year = 2003 | accessdate = 2009-08-29 }}</ref> [[Standard ML]]<ref>{{cite conference | last = Sims | first = Steve | title = Building a Startup with Standard ML | url = http://cufp.galois.com/2006/slides/SteveSims.pdf | year = 2006 | conference = CUFP 2006 | accessdate = 2009-08-29 }}</ref><ref>{{cite conference | last = Laurikari | first = Ville | title = Functional Programming in Communications Security. | url = http://cufp.galois.com/2007/abstracts.html#VilleLaurikari | year = 2007 | conference = CUFP 2007 | accessdate = 2009-08-29 }}</ref> and [[Clojure]].<ref>{{cite web | url = http://www.infoq.com/news/2009/01/clojure_production | last = Lorimer | first = R. J. | title = Live Production Clojure Application Announced }}</ref>
==In education==
Functional programming is being used as a method to teach problem solving, algebra and geometric concepts.<ref name="bootstrapworld">{{Triangulation|196|Emmanuel Schanzer of Bootstrap}}</ref>
It has also been used as a tool to teach classical mechanics in [[Structure and Interpretation of Classical Mechanics]].
== See also ==
{{Portal|Computer programming}}
* [[Purely functional programming]]
* [[Comparison of programming paradigms]]
* [[Eager evaluation]]
* [[List of functional programming topics]]
* [[Nested function]]
* [[Inductive functional programming]]
* [[Functional reactive programming]]
== References ==
{{reflist|colwidth=30em|refs=
<ref name="clinger1987">{{cite journal | last = Clinger | first = Will | title = MultiTasking and MacScheme | magazine = MacTech | volume = 3 | issue = 12 | year = 1987 | url = http://www.mactech.com/articles/mactech/Vol.03/03.12/Multitasking/index.html | accessdate = 2008-08-28 }}</ref>
<ref name="hartheimer1987">{{cite journal | last = Hartheimer | first = Anne | title = Programming a Text Editor in MacScheme+Toolsmith | magazine = MacTech | volume = 3 | issue = 1 | year = 1987 | url = http://www.mactech.com/articles/mactech/Vol.03/03.1/SchemeWindows/index.html | accessdate = 2008-08-28 }}</ref>
<ref name="kidd2007">{{cite conference | last = Kidd | first = Eric | url = http://cufp.galois.com/2007/abstracts.html#EricKidd | title = Terrorism Response Training in Scheme | conference = CUFP 2007 | accessdate = 2009-08-26 }}</ref>
<ref name="cleis2006">{{cite conference | last = Cleis | first = Richard | url = http://cufp.galois.com/2006/abstracts.html#RichardCleis | title = Scheme in Space | conference = CUFP 2006 | accessdate = 2009-08-26 }}</ref>
<ref name="erlang-faq">{{cite web | title = Who uses Erlang for product development? | work=Frequently asked questions about Erlang | url = http://www.erlang.org/faq/faq.html#AEN50 | accessdate = 2007-08-05 }}</ref>
<ref name="armstrong2007">{{cite conference | last = Armstrong | first = Joe | title = A history of Erlang | conference = Third ACM SIGPLAN Conference on History of Programming Languages | ___location = San Diego, California | date = June 2007 | url = http://doi.acm.org/10.1145/1238844.1238850 | accessdate = 2009-08-29 }}</ref>
<ref name="larson2009">{{cite journal | last = Larson | first = Jim | title = Erlang for concurrent programming | journal = Communications of the ACM | volume= 52 | issue= 3 | date = March 2009 | doi=10.1145/1467247.1467263 | page=48 }}</ref>
<ref name="minksy2008">{{cite journal | last = Minsky | first = Yaron | last2 = Weeks | first2 = Stephen | title = Caml Trading — experiences with functional programming on Wall Street | journal = Journal of Functional Programming | volume = 18 | issue = 4 | pages = 553–564 | publisher = Cambridge University Press | ___location = |date=July 2008 | url = http://journals.cambridge.org/action/displayAbstract?aid=1899164 | doi = 10.1017/S095679680800676X | accessdate = 2008-08-27 }}</ref>
<ref name="leroy2007">{{cite conference | last = Leroy | first = Xavier | title = Some uses of Caml in Industry | url = http://cufp.galois.com/2007/slides/XavierLeroy.pdf | conference = CUFP 2007 | accessdate = 2009-08-26 }}</ref><ref name="haskell-industry">{{cite web | title = Haskell in industry | work = Haskell Wiki | url = http://www.haskell.org/haskellwiki/Haskell_in_industry | accessdate = 2009-08-26 | quote=Haskell has a diverse range of use commercially, from aerospace and defense, to finance, to web startups, hardware design firms and lawnmower manufacturers. }}</ref>
<ref name="effective-scala">{{cite web | title = Effective Scala | work = Scala Wiki | url = http://twitter.github.com/effectivescala/?sd | accessdate = 2012-02-21 | quote=Effective Scala. }}</ref><ref name="racket-video-games">{{cite web | title = State-Based Scripting in Uncharted 2 | url = http://www.gameenginebook.com/gdc09-statescripting-uncharted2.pdf | archiveurl = https://web.archive.org/web/20121215014637/http://www.gameenginebook.com/gdc09-statescripting-uncharted2.pdf | archivedate = 2012-12-15 | accessdate = 2011-08-08 }}</ref>
<ref name="hudak2007">{{cite conference | last = Hudak | first = Paul |author2=Hughes, J. |author3=Jones, S. P. |author4=Wadler, P. | authorlink=Paul Hudak | title = A history of Haskell: being lazy with class | url=http://dl.acm.org/citation.cfm?doid=1238844.1238856 | conference = Third ACM SIGPLAN Conference on History of Programming Languages | ___location = San Diego, California| date = June 2007 | doi = 10.1145/1238844.1238856 | accessdate = 2013-09-26 }}</ref>
<ref name="useR">{{cite web | url = http://www.r-project.org/useR-2006/program.html | title = The useR! 2006 conference schedule includes papers on the commercial use of R |publisher=R-project.org | date = 2006-06-08 | accessdate = 2011-06-20 }}</ref><ref name="Chambers">{{cite book | last = Chambers | first = John M. | authorlink=John Chambers (programmer) | title = Programming with Data: A Guide to the S Language | publisher=Springer Verlag | year = 1998 | pages = 67–70 | isbn = 978-0-387-98503-9 }}</ref><ref name="Amath-CO">{{cite web | author = Department of Applied Math, University of Colorado | title = Functional vs. Procedural Programming Language | url = http://amath.colorado.edu/computing/mmm/funcproc.html | archiveurl = https://web.archive.org/web/20071113175801/http://amath.colorado.edu/computing/mmm/funcproc.html | archivedate = 2007-11-13 | accessdate = 2006-08-28 }}</ref>
<ref name="Novatchev">{{cite web | url = http://www.topxml.com/xsl/articles/fp/ | author = Dimitre Novatchev | title = The Functional Programming Language XSLT — A proof through examples | accessdate = May 27, 2006 | work=TopXML }}</ref><ref name="Mertz">{{cite web | url = http://gnosis.cx/publish/programming/xml_models_fp.html | author = David Mertz | title = XML Programming Paradigms (part four): Functional Programming approached to XML processing | accessdate = May 27, 2006 | work=IBM developerWorks }}</ref>
<ref name="Chamberlin_Boyce">{{cite journal | title = SEQUEL: A structured English query language | author = [[Donald D. Chamberlin]] and [[Raymond F. Boyce]] | journal = Proceedings of the 1974 ACM SIGFIDET | pages = 249–264 | year = 1974 }}</ref><ref name="Sim-Diasca">{{cite web | title = Sim-Diasca: a large-scale discrete event concurrent simulation engine in Erlang | url = http://research.edf.com/research-and-the-scientific-community/software/sim-diasca-80704.html |date=November 2011 }}</ref>
<ref name="Spiewak">{{cite web | url = http://www.codecommit.com/blog/scala/implementing-persistent-vectors-in-scala | author = Daniel Spiewak | title = Implementing Persistent Vectors in Scala | accessdate = Apr 17, 2012}}</ref>
<ref name="Opal (programming language)">[[Opal (programming language)|OPtimized Applicative Language]]</ref>
}}
== Further reading ==
* {{cite book|last1=Abelson|first1=Hal|authorlink1=Hal Abelson|last2=Sussman|first2=Gerald Jay|authorlink2=Gerald Jay Sussman | title = Structure and Interpretation of Computer Programs | url = http://mitpress.mit.edu/sicp/ | year = 1985|publisher=MIT Press}}
* Cousineau, Guy and Michel Mauny. ''The Functional Approach to Programming''. Cambridge, UK: [[Cambridge University Press]], 1998.
* Curry, Haskell Brooks and Feys, Robert and Craig, William. ''Combinatory Logic''. Volume I. North-Holland Publishing Company, Amsterdam, 1958.
* {{cite book | last1 = Curry | first1 = Haskell B. | first2 = J. Roger | last2 = Hindley | first3 = Jonathan P. | last3 = Seldin | authorlink1 = Haskell Curry | authorlink2 = J. Roger Hindley | authorlink3 = Jonathan P. Seldin | title = Combinatory Logic | volume = Vol. II | year = 1972 | publisher = North Holland | ___location = Amsterdam | isbn = 0-7204-2208-6 }}
* Dominus, Mark Jason. ''[http://hop.perl.plover.com/book/pdf/HigherOrderPerl.pdf Higher-Order Perl]''. [[Morgan Kaufmann]]. 2005.
* {{cite book|last1=Felleisen|first1=Matthias|last2=Findler|first2=Robert|last3=Flatt|first3=Matthew|first4=Shriram |last4=Krishnamurthi | title = How to Design Programs | url = http://www.htdp.org | year = 2001|publisher=MIT Press}}
* Graham, Paul. ''ANSI Common LISP''. Englewood Cliffs, New Jersey: [[Prentice Hall]], 1996.
* MacLennan, Bruce J. ''Functional Programming: Practice and Theory''. Addison-Wesley, 1990.
* {{cite book|last1=O'Sullivan|first1=Brian|last2=Stewart|first2=Don|last3=Goerzen|first3=John | title = Real World Haskell | url = http://book.realworldhaskell.org/read/ | year = 2008|publisher=O'Reilly}}
* Pratt, Terrence, W. and Marvin V. Zelkowitz. ''Programming Languages: Design and Implementation''. 3rd ed. Englewood Cliffs, New Jersey: [[Prentice Hall]], 1996.
* Salus, Peter H. ''Functional and Logic Programming Languages''. Vol. 4 of Handbook of Programming Languages. Indianapolis, Indiana: [[Macmillan Technical Publishing]], 1998.
* Thompson, Simon. ''Haskell: The Craft of Functional Programming''. Harlow, England: [[Addison-Wesley Longman Limited]], 1996.
== External links ==
{{Spoken Wikipedia|En-Functional_programming.ogg|2011-08-25}}
*{{cite web
| last = Ford
| first = Neal
| title = Functional thinking: Why functional programming is on the rise
| accessdate = 2013-02-24
| date = 2012-01-29
| url = http://www.ibm.com/developerworks/java/library/j-ft20/index.html
}}
* {{cite web
| last = Akhmechet
| first = Slava
| title = defmacro – Functional Programming For The Rest of Us
| accessdate = 2013-02-24
| date = 2006-06-19
| url = http://www.defmacro.org/ramblings/fp.html
}} An introduction
* ''Functional programming in Python'' (by David Mertz): [http://gnosis.cx/publish/programming/charming_python_13.html part 1], [http://gnosis.cx/publish/programming/charming_python_16.html part 2], [http://gnosis.cx/publish/programming/charming_python_19.html part 3]
{{Programming language}}
{{Authority control}}
{{DEFAULTSORT:Functional programming}}
[[Category:Programming paradigms]]
[[Category:Functional programming| ]]' |
Whether or not the change was made through a Tor exit node (tor_exit_node ) | 0 |
Unix timestamp of change (timestamp ) | 1488806263 |