functional programming

{{Short description|Programming paradigm based on applying and composing functions}}

{{For|subroutine-oriented programming|Procedural programming}}

In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that map values to other values, rather than a sequence of imperative statements which update the running state of the program.

In functional programming, functions are treated as first-class citizens, meaning that they can be bound to names (including local identifiers), passed as arguments, and returned from other functions, just as any other data type can. This allows programs to be written in a declarative and composable style, where small functions are combined in a modular manner.

Functional programming is sometimes treated as synonymous with purely functional programming, a subset of functional programming that treats all functions as deterministic mathematical functions, or pure functions. When a pure function is called with some given arguments, it will always return the same result, and cannot be affected by any mutable state or other side effects. This is in contrast with impure procedures, common in imperative programming, which can have side effects (such as modifying the program's state or taking input from a user). Proponents of purely functional programming claim that by restricting side effects, programs can have fewer bugs, be easier to debug and test, and be more suited to formal verification.{{cite journal |last=Hudak |first=Paul |author-link=Paul Hudak |title=Conception, evolution, and application of functional programming languages |journal=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 |doi=10.1145/72551.72554 |s2cid=207637854 |accessdate=2013-08-10 |archivedate=2016-01-31 |archiveurl=https://web.archive.org/web/20160131083528/http://www.dbnet.ece.ntua.gr/~adamo/languages/books/p359-hudak.pdf |url-status=deviated }}

Functional programming has its roots in academia, evolving from the lambda calculus, a formal system of computation based only on functions. Functional programming has historically been less popular than imperative programming, but many functional languages are seeing use today in industry and education, including Common Lisp, Scheme, Clojure, Wolfram Language,{{cite web |title=Wolfram Language Guide: Functional Programming |url=http://reference.wolfram.com/language/guide/FunctionalProgramming.html |year=2015 |access-date=2015-08-24}} Racket, Erlang, Elixir,{{Cite web|title=The Elixir Programming Language|url=https://elixir-lang.org/|access-date=2021-02-14}} OCaml, Haskell, and F#.{{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 |access-date=2009-08-29 |archivedate=2015-07-08 |archiveurl=https://web.archive.org/web/20150708125937/http://cufp.galois.com/2008/abstracts.html#MansellHoward |url-status=dead }}{{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 |access-date=2009-08-29 |archive-url=https://web.archive.org/web/20091017070140/http://cufp.galois.com/2009/abstracts.html#AlexPeakeAdamGranicz |archive-date=2009-10-17 |url-status=dead }} Lean is a functional programming language commonly used for verifying mathematical theorems.{{cite conference |conference=Conference on Automated Deduction |title=The Lean 4 Theorem Prover and Programming Language |last1=de Moura |first1=Leonardo |last2=Ullrich |first2=Sebastian |date=July 2021 |book-title=Lecture Notes in Artificial Intelligence |volume=12699 |pages=625–635 |issn=1611-3349 |doi=10.1007/978-3-030-79876-5_37 |doi-access=free}} Functional programming is also key to some languages that have found success in specific domains, like JavaScript in the Web,{{Cite web|last=Banz|first=Matt|date=2017-06-27|title=An introduction to functional programming in JavaScript|url=https://opensource.com/article/17/6/functional-javascript|access-date=2021-01-09|website=Opensource.com|language=en}} R in statistics, J, K and Q in financial analysis, and XQuery/XSLT for XML. Domain-specific declarative languages like SQL and Lex/Yacc use some elements of functional programming, such as not allowing mutable values. In addition, many other programming languages support programming in a functional style or have implemented features from functional programming, such as C++11, C#,{{Citation|title=Functional Programming with C# - Simon Painter - NDC Oslo 2020| date=8 August 2021 |url=https://www.youtube.com/watch?v=gvyTB4aMI4o| archive-url=https://ghostarchive.org/varchive/youtube/20211030/gvyTB4aMI4o| archive-date=2021-10-30|language=en|access-date=2021-10-23}}{{cbignore}} Kotlin,{{Cite web|url=https://kotlinlang.org/docs/tutorials/kotlin-for-py/functional-programming.html|title=Functional programming - Kotlin Programming Language|website=Kotlin|access-date=2019-05-01}} Perl,{{cite book |last=Dominus |first=Mark J. |author-link=Mark Jason Dominus |title=Higher-Order Perl |publisher=Morgan Kaufmann |year=2005 |isbn=978-1-55860-701-9 |title-link=Higher-Order Perl}} PHP,{{cite book |last=Holywell |first=Simon |title=Functional Programming in PHP |publisher=php[architect] |year=2014 |isbn=9781940111056}} Python,{{cite web |url=https://www.python.org/community/pycon/dc2004/papers/24/metaclasses-pycon.pdf |archive-url=https://web.archive.org/web/20090530030205/http://www.python.org/community/pycon/dc2004/papers/24/metaclasses-pycon.pdf |archive-date=30 May 2009 |title=Python Metaclasses: Who? Why? When? |last=The Cain Gang Ltd. |access-date=27 June 2009 |url-status=dead |df=dmy-all }} Go,{{Cite web|last=|first=|date=22 December 2020|title=GopherCon 2020: Dylan Meeus - Functional Programming with Go|url=https://www.youtube.com/watch?v=wqs8n5Uk5OM|access-date=|website=YouTube}} Rust,{{Cite web|title=Functional Language Features: Iterators and Closures - The Rust Programming Language|url=https://doc.rust-lang.org/book/ch13-00-functional-features.html|access-date=2021-01-09|website=doc.rust-lang.org}} Raku,{{cite web|last=Vanderbauwhede |first=Wim |url=https://wimvanderbauwhede.github.io/articles/decluttering-with-functional-programming/|archive-url=https://web.archive.org/web/20200728013926/https://wimvanderbauwhede.github.io/articles/decluttering-with-functional-programming/|archive-date=28 July 2020|title=Cleaner code with functional programming |date=18 July 2020 |access-date=6 October 2020}} Scala, and Java (since Java 8).

History

The lambda calculus, developed in the 1930s by Alonzo Church, is a formal system of computation built from function application. In 1937 Alan Turing proved that the lambda calculus and Turing machines are equivalent models of computation,{{cite journal|first=A. M.|last=Turing|doi=10.2307/2268280|title=Computability and λ-definability|year=1937|journal=The Journal of Symbolic Logic|pages=153–163|volume=2|issue=4|publisher=Cambridge University Press|jstor=2268280|s2cid=2317046}} showing that the lambda calculus is Turing complete. Lambda calculus forms the basis of all functional programming languages. An equivalent theoretical formulation, combinatory logic, was developed by Moses Schönfinkel and Haskell Curry in the 1920s and 1930s.{{cite book|author1=Haskell Brooks Curry|author2=Robert Feys|title=Combinatory Logic|url=https://archive.org/details/combinatorylogic0002curr|url-access=registration|access-date=10 February 2013|year=1958|publisher=North-Holland Publishing Company}}

Church later developed a weaker system, the simply typed lambda calculus, which extended the lambda calculus by assigning a data type to all terms.{{cite journal |last1=Church |author-link=Alonzo Church |first1=A. |year=1940 |title=A Formulation of the Simple Theory of Types |journal=Journal of Symbolic Logic |volume=5 |issue=2 |pages=56–68 |doi=10.2307/2266170 |jstor=2266170| s2cid=15889861}} This forms the basis for statically typed functional programming.

The first high-level functional programming language, Lisp, was developed in the late 1950s for the IBM 700/7000 series of scientific computers by John McCarthy while at Massachusetts Institute of Technology (MIT).{{cite conference |first=John |last=McCarthy |author-link=John McCarthy (computer scientist) |title=History of Lisp |journal=History of Programming Languages |pages=173–185 |date=June 1978 |url=http://jmc.stanford.edu/articles/lisp/lisp.pdf|doi=10.1145/800025.808387 |place=Los Angeles, CA}} Lisp functions were defined using Church's lambda notation, extended with a label construct to allow recursive functions.{{cite journal|author=John McCarthy|author-link=John McCarthy (computer scientist)|title=Recursive functions of symbolic expressions and their computation by machine, Part I.|journal=Communications of the ACM|volume=3|issue=4|year=1960|pages=184–195|url=http://jmc.stanford.edu/articles/recursive/recursive.pdf|publisher=ACM New York, NY, US|doi=10.1145/367177.367199|s2cid=1489409}} Lisp first introduced many paradigmatic features of functional programming, though early Lisps were multi-paradigm languages, and incorporated support for numerous programming styles as new paradigms evolved. Later dialects, such as Scheme and Clojure, and offshoots such as Dylan and 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.{{cite book|author1=Guy L. Steele |author2=Richard P. Gabriel |title=History of programming languages---II |chapter=The evolution of Lisp |pages= 233–330 |date=February 1996 |url=http://dreamsongs.com/Files/HOPL2-Uncut.pdf |doi= 10.1145/234286.1057818 |isbn=978-0-201-89502-5 |s2cid=47047140}}

Information Processing Language (IPL), 1956, is sometimes cited as the first computer-based functional programming language.The memoir of Herbert A. Simon (1991), Models of My Life pp.189-190 {{ISBN|0-465-04640-1}} claims that he, Al Newell, and Cliff Shaw are "...commonly adjudged to be the parents of [the] artificial intelligence [field]," for writing Logic Theorist, a program that proved theorems from Principia Mathematica automatically. To accomplish this, they had to invent a language and a paradigm that, viewed retrospectively, embeds functional programming. It is an assembly-style language for manipulating lists of symbols. It does have a notion of generator, which amounts to a function that accepts a function as an argument, and, since it is an assembly-level language, code can be data, so IPL can be regarded as having higher-order functions. However, it relies heavily on the mutating list structure and similar imperative features.

Kenneth E. Iverson developed 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. In the early 1990s, Iverson and Roger Hui created J. In the mid-1990s, Arthur Whitney, who had previously worked with Iverson, created K, which is used commercially in financial industries along with its descendant Q.

In the mid-1960s, Peter Landin invented SECD machine,{{cite journal

| last=Landin

| first=Peter J.

| year=1964

| title=The mechanical evaluation of expressions

| journal=The Computer Journal

| volume=6

| issue=4

| pages=308–320

| publisher=British Computer Society

| doi=10.1093/comjnl/6.4.308

| doi-access=free

}} the first abstract machine for a functional programming language,{{Cite book |last1=Diehl |first1=Stephan |last2=Hartel |first2=Pieter |last3=Sestoft |first3=Peter |date=2000 |chapter=Abstract machines for programming language implementation |title=Future Generation Computer Systems |volume=16 |issue=7 |pages=739–751}} described a correspondence between ALGOL 60 and the lambda calculus,{{cite journal

| last=Landin

| first=Peter J.

|date=February 1965a

| title=Correspondence between ALGOL 60 and Church's Lambda-notation: part I

| journal=Communications of the ACM

| volume=8

| issue=2

| pages=89–101

| publisher=Association for Computing Machinery

| doi=10.1145/363744.363749

| s2cid=6505810

| doi-access=free

}}{{cite journal

| last=Landin

| first=Peter J.

|date=March 1965b

| title=A correspondence between ALGOL 60 and Church's Lambda-notation: part II

| journal=Communications of the ACM

| volume=8

| issue=3

| pages=158–165

| publisher=Association for Computing Machinery

| doi=10.1145/363791.363804

| s2cid=15781851

| doi-access=free

}} and proposed the ISWIM programming language.{{cite journal

| last=Landin

| first=Peter J.

| date=March 1966b

| title=The next 700 programming languages

| journal=Communications of the ACM

| volume=9

| issue=3

| pages=157–166

| publisher=Association for Computing Machinery

| doi=10.1145/365230.365257

| s2cid=13409665

| doi-access=free

}}

John Backus presented FP in his 1977 Turing Award lecture "Can Programming Be Liberated From the von Neumann Style? A Functional Style and its Algebra of Programs".{{Cite journal |doi=10.1145/359576.359579| title=Can programming be liberated from the von Neumann style?: A functional style and its algebra of programs| journal=Communications of the ACM| volume=21| issue=8| pages=613–641| year=1978| last1=Backus |first1=J. |doi-access=free}} 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 now associated with functional programming.

The 1973 language ML was created by Robin Milner at the University of Edinburgh, and David Turner developed the language SASL at the University of St Andrews. Also in Edinburgh in the 1970s, Burstall and Darlington developed the functional language NPL.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) NPL was based on Kleene Recursion Equations and was first introduced in their work on program transformation.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) Burstall, MacQueen and Sannella then incorporated the polymorphic type checking from ML to produce the language Hope.R.M. Burstall, D.B. MacQueen and D.T. Sannella. HOPE: an experimental applicative language. Proceedings 1980 LISP Conference, Stanford, 136–143 (1980). ML eventually developed into several dialects, the most common of which are now OCaml and Standard ML.

In the 1970s, Guy L. Steele and Gerald Jay Sussman developed Scheme, as described in the Lambda Papers and the 1985 textbook Structure and Interpretation of Computer Programs. Scheme was the first dialect of lisp to use lexical scoping and to require tail-call optimization, features that encourage functional programming.

In the 1980s, Per Martin-Löf developed intuitionistic type theory (also called constructive type theory), which associated functional programs with constructive proofs expressed as dependent types. This led to new approaches to interactive theorem proving and has influenced the development of subsequent functional programming languages.{{citation needed|date=July 2018}}

The lazy functional language, Miranda, developed by David Turner, initially appeared in 1985 and had a strong influence on Haskell. With Miranda being proprietary, Haskell began with a consensus in 1987 to form an open standard for functional programming research; implementation releases have been ongoing as of 1990.

More recently it has found use in niches such as parametric CAD in the OpenSCAD language built on the CGAL framework, although its restriction on reassigning values (all values are treated as constants) has led to confusion among users who are unfamiliar with functional programming as a concept.{{cite web|url=https://forum.openscad.org/Make-discovering-assign-easier-td10964.html|website=OpenSCAD|title =Make discovering assign() easier!|archive-url=https://web.archive.org/web/20230419060430/https://forum.openscad.org/Make-discovering-assign-easier-td10964.html |archive-date=2023-04-19 }}

Functional programming continues to be used in commercial settings.{{cite web |url=https://arstechnica.com/gadgets/2018/03/developers-love-trendy-new-languages-but-earn-more-with-functional-programming/ |title=Developers love trendy new languages but earn more with functional programming |author=Peter Bright |date=March 13, 2018 |website=Ars Technica}}{{cite web |url=https://www.computing.co.uk/ctg/analysis/3003123/the-slow-but-steady-rise-of-functional-programming |title=The stealthy rise of functional programming |author=John Leonard |date=January 24, 2017 |publisher=Computing}}{{cite magazine |url=https://www.infoworld.com/article/3190185/software/is-functional-programming-better-for-your-startup.html |title=Is functional programming better for your startup? |author=Leo Cheung |date=May 9, 2017 |magazine=InfoWorld}}

Concepts

A number of conceptsSean Tull - Monoidal Categories for Formal Concept Analysis. and paradigms are specific to functional programming, and generally foreign to imperative programming (including object-oriented programming). However, programming languages often cater to several programming paradigms, so programmers using "mostly imperative" languages may have utilized some of these concepts.{{cite web |url=http://byte.com/art/9408/sec11/art1.htm |archive-url=https://web.archive.org/web/20060827094123/http://byte.com/art/9408/sec11/art1.htm |archive-date=2006-08-27 |title=Functional Programming Comes of Age |first=Dick |last=Pountain |work=Byte (August 1994) |access-date=August 31, 2006 |url-status=dead }}

= First-class and higher-order functions =

{{main|First-class function|Higher-order function}}

Higher-order functions 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 d/dx, which returns the derivative of a function f.

Higher-order functions are closely related to first-class functions 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 for 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 that applies a function to its arguments one at a time, with each application returning a new function that accepts the next argument. This lets a programmer succinctly express, for example, the successor function as the addition operator partially applied to the natural number one.

= Pure functions =

{{main|Pure function}}

Pure functions (or expressions) have no 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 or idempotence), i.e., calling the pure function again with the same arguments returns the same result. (This can enable caching optimizations such as memoization.)
  • If there is no data dependency between two pure expressions, their order can be reversed, or they can be performed in parallel and they cannot interfere with one another (in other terms, the evaluation of any pure expression is thread-safe).
  • 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).

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 gcc, add extra keywords for a programmer to explicitly mark external functions as pure, to enable such optimizations. Fortran 95 also lets functions be designated pure.{{cite web |title=ISO/IEC JTC 1/SC 22/WG5/N2137 – Fortran 2015 Committee Draft (J3/17-007r2) |publisher=International Organization for Standardization |date=July 6, 2017 |url=https://wg5-fortran.org/N2101-N2150/N2137.pdf |pages=336–338}} C++11 added constexpr keyword with similar semantics.

= Recursion =

{{Main|Recursion (computer science)}}

Iteration (looping) in functional languages is usually accomplished via recursion. Recursive functions invoke themselves, letting an operation be repeated until it reaches the base case. In general, recursion requires maintaining a stack, which consumes space in a linear amount to the depth of recursion. This could make recursion prohibitively expensive to use instead of imperative loops. However, a special form of recursion known as tail recursion can be recognized and optimized by a compiler into the same code used to implement iteration in imperative languages. Tail recursion optimization can be implemented by transforming the program into continuation passing style during compiling, among other approaches.

The Scheme language standard requires implementations to support proper tail recursion, meaning they must allow an unbounded number of active tail calls.{{cite web|url=http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-8.html#node_sec_5.11 |title=Revised^6 Report on the Algorithmic Language Scheme |publisher=R6rs.org |access-date=2013-03-21}}{{cite web|url=http://www.r6rs.org/final/html/r6rs-rationale/r6rs-rationale-Z-H-7.html#node_sec_5.3 |title=Revised^6 Report on the Algorithmic Language Scheme - Rationale |publisher=R6rs.org |access-date=2013-03-21}} Proper tail recursion is not simply an optimization; it is a language feature that assures users that they can use recursion to express a loop and doing so would be safe-for-space.{{cite book|chapter=Proper tail recursion and space efficiency|last=Clinger|first=William|title=Proceedings of the ACM SIGPLAN 1998 conference on Programming language design and implementation - PLDI '98|date=1998|pages=174–185|doi=10.1145/277650.277719|isbn=0897919874|s2cid=16812984}} Moreover, contrary to its name, it accounts for all tail calls, not just tail recursion. While proper tail recursion is usually implemented by turning code into imperative loops, implementations might implement it in other ways. For example, Chicken intentionally maintains a stack and lets the stack overflow. However, when this happens, its garbage collector will claim space back,{{cite web |url=http://home.pipeline.com/~hbaker1/CheneyMTA.html |title=CONS Should Not CONS Its Arguments, Part II: Cheney on the M.T.A. |last=Baker |first=Henry |date=1994 |access-date=2020-04-29 |archivedate=2006-03-03 |archiveurl=https://web.archive.org/web/20060303155622/http://home.pipeline.com/~hbaker1/CheneyMTA.html |url-status=deviated }} allowing an unbounded number of active tail calls even though it does not turn tail recursion into a loop.

Common patterns of recursion can be abstracted away using higher-order functions, with catamorphisms and anamorphisms (or "folds" and "unfolds") being the most obvious examples. Such recursion schemes play a role analogous to built-in control structures such as loops in imperative languages.

Most general purpose functional programming languages allow unrestricted recursion and are Turing complete, which makes the halting 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). 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.{{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}}

= Strict versus non-strict evaluation =

{{Main|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 fails. For example, the expression:

print length([2+1, 3*2, 1/0, 5-4])

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

The usual implementation strategy for lazy evaluation in functional languages is graph reduction.[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 Lazy evaluation is used by default in several pure functional languages, including Miranda, Clean, and 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.{{cite web |url=http://www.cse.chalmers.se/~rjmh/Papers/whyfp.html |title=Why Functional Programming Matters |author-link=John Hughes (computer scientist) |first=John |last=Hughes |year=1984}} Launchbury 1993 describes some difficulties that lazy evaluation introduces, particularly in analyzing a program's storage requirements, and proposes an operational semantics to aid in such analysis.{{cite conference |last=Launchbury |first=John |author-link=John Launchbury |title=A Natural Semantics for Lazy Evaluation |date=March 1993 |conference=Symposium on Principles of Programming Languages |location=Charleston, South Carolina |publisher=ACM |pages=144–154 |doi=10.1145/158511.158618 |doi-access=free}} Harper 2009 proposes including both strict and lazy evaluation in the same language, using the language's type system to distinguish them.{{cite book |url=https://www.cs.cmu.edu/~rwh/plbook/book.pdf |archive-url=https://web.archive.org/web/20160407095249/https://www.cs.cmu.edu/~rwh/plbook/book.pdf |archive-date=2016-04-07 |title=Practical Foundations for Programming Languages |author=Robert W. Harper |author-link=Robert Harper (computer scientist) |year=2009}}

= Type systems =

{{main|Type system}}

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 positive errors, as opposed to the untyped lambda calculus, that accepts all valid programs at compilation time and risks false negative errors, used in Lisp and its variants (such as Scheme), as they reject all invalid programs at runtime when the information is enough to not reject valid programs. The use of algebraic data types 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, Cayenne, and Epigram are based on intuitionistic type theory, which lets types depend on terms. Such types are called dependent types. These type systems do not have decidable type inference and are difficult to understand and program with.{{cite journal |last=Huet |first=Gérard P. |date=1973 |title=The Undecidability of Unification in Third Order Logic |journal=Information and Control |doi=10.1016/s0019-9958(73)90301-x |volume=22 |issue=3 |pages=257–267}}{{cite thesis |type=Ph.D. |last=Huet |first=Gérard |date=Sep 1976 |title=Resolution d'Equations dans des Langages d'Ordre 1,2,...ω |language=fr |publisher=Universite de Paris VII}}{{cite book |last=Huet |first=Gérard |date=2002 |editor1-last=Carreño |editor1-first=V. |editor2-last=Muñoz |editor2-first=C. |editor3-last=Tahar |editor3-first=S. |chapter=Higher Order Unification 30 years later |title=Proceedings, 15th International Conference TPHOL |volume=2410 |pages=3–12 |publisher=Springer |series=LNCS |chapter-url=http://pauillac.inria.fr/~huet/PUBLIC/Hampton.pdf}}{{cite journal |first=J. B. |last=Wells |title=Typability and type checking in the second-order lambda-calculus are equivalent and undecidable |citeseerx=10.1.1.31.3590 |journal=Tech. Rep. 93-011 |year=1993 |pages=176–185}} But dependent types can express arbitrary propositions in higher-order logic. Through the Curry–Howard isomorphism, then, well-typed programs in these languages become a means of writing formal mathematical proofs from which a compiler can generate 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 language C that is written in Coq and formally verified.{{cite web |url=http://compcert.inria.fr/doc/index.html |title=The Compcert verified compiler |last1=Leroy|first1=Xavier|date=17 September 2018}}

A limited form of dependent types called generalized algebraic data types (GADT's) can be implemented in a way that provides some of the benefits of dependently typed programming while avoiding most of its inconvenience.{{cite journal |url=http://research.microsoft.com/en-us/um/people/simonpj/papers/gadt/ |title=Simple unification-based type inference for GADTs |first1=Simon |last1=Peyton Jones |first2=Dimitrios |last2=Vytiniotis |first3=Stephanie |last3=Weirich |author3-link= Stephanie Weirich |author4=Geoffrey Washburn |journal=Icfp 2006 |pages=50–61 |date=April 2006}} GADT's are available in the Glasgow Haskell Compiler, in OCaml{{Cite web|title=OCaml Manual|url=https://caml.inria.fr/pub/docs/manual-ocaml/gadts.html|access-date=2021-03-08|website=caml.inria.fr}} and in Scala,{{Cite web|title=Algebraic Data Types|url=https://docs.scala-lang.org/scala3/book/types-adts-gadts.html|access-date=2021-03-08|website=Scala Documentation}} and have been proposed as additions to other languages including Java and C#.{{cite conference |title=Generalized Algebraic Data Types and Object-Oriented Programming |first1=Andrew |last1=Kennedy |first2=Claudio V. |last2=Russo |conference=OOPSLA |date=October 2005 |publisher=ACM |location=San Diego, California |url=https://www.microsoft.com/en-us/research/publication/generalized-algebraic-data-types-and-object-oriented-programming/ |archive-url=https://web.archive.org/web/20061229164852/http://research.microsoft.com/~akenn/generics/gadtoop.pdf |archive-date=2006-12-29 |doi=10.1145/1094811.1094814 |isbn=9781595930316}}

= Referential transparency =

{{Main|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.{{cite web|last1=Hughes |first1=John |title=Why Functional Programming Matters |url=http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf |publisher=Chalmers University of Technology}}

Consider C assignment statement x=x*10, this changes the value assigned to the variable x. Let us say that the initial value of x was 1, then two consecutive evaluations of the variable x yields 10 and 100 respectively. Clearly, replacing x=x*10 with either 10 or 100 gives a program a different meaning, and so the expression is not referentially transparent. In fact, assignment statements are never referentially transparent.

Now, consider another function such as int plusone(int x) {return x+1;} is transparent, as it does not implicitly change the input x and thus has no such side effects.

Functional programs exclusively use this type of function and are therefore referentially transparent.

=Data structures=

{{main|Purely functional data structure}}

Purely functional data structures are often represented in a different way to their imperative counterparts.[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}} For example, the array with constant access and update times is a basic component of most imperative languages, and many imperative data-structures, such as the hash table and binary heap, are based on arrays. Arrays can be replaced by maps or random access lists, which admit purely functional implementation, but have logarithmic access and update times. Purely functional data structures have persistence, a property of keeping previous versions of the data structure unmodified. In Clojure, persistent data structures are used as functional alternatives to their imperative counterparts. Persistent vectors, for example, use trees for partial updating. Calling the insert method will result in some but not all nodes being created.{{Cite web|url=http://www.hypirion.com/musings/understanding-persistent-vector-pt-1|title=polymatheia - Understanding Clojure's Persistent Vector, pt. 1 |last=L’orange |first=Jean Niklas |website=Polymatheia |access-date=2018-11-13}}

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 effects, which are used in imperative programming to implement state and I/O. Pure functional programming completely prevents side-effects and provides 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.

= Imperative vs. functional programming =

The following two examples (written in JavaScript) achieve the same effect: they multiply all even numbers in an array by 10 and add them all, storing the final sum in the variable "result".

Traditional imperative loop:

const numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let result = 0;

for (let i = 0; i < numList.length; i++) {

if (numList[i] % 2 === 0) {

result += numList[i] * 10;

}

}

Functional programming with higher-order functions:

const result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

.filter(n => n % 2 === 0)

.map(a => a * 10)

.reduce((a, b) => a + b, 0);

Sometimes the abstractions offered by functional programming might lead to development of more robust code that avoids certain issues that might arise when building upon large amount of complex, imperative code, such as off-by-one errors (see Greenspun's tenth rule).

= 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 implements them using monads, derived from category theory.Michael Barr, Charles Well - Category theory for computer science. 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).{{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/ |access-date=2008-02-14}}

Functional languages also simulate states by passing around immutable states. This can be done by making a function accept the state as one of its parameters, and return a new state together with the result, leaving the old state unchanged.{{Cite web|url=https://fsharpforfunandprofit.com/posts/13-ways-of-looking-at-a-turtle/#2-basic-fp---a-module-of-functions-with-immutable-state|title=Thirteen ways of looking at a turtle |website=fF# for fun and profit|language=en|access-date=2018-11-13}}

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.{{citation needed|date=July 2018}}

Alternative methods such as Hoare logic and uniqueness have been developed to track side effects in programs. Some modern research languages use effect systems to make the presence of side effects explicit.{{cite book |last1=Hartmanis |first1=Juris |date=1986 |pages=123–135 |url=https://doi.org/10.1007/3-540-16761-7_62 |access-date=2024-12-12 |place=Berlin, Heidelberg |publisher=Springer Berlin Heidelberg |isbn=978-3-540-16761-7 |last2=Hemachandra |first2=Lane|title=Automata, Languages and Programming |chapter=Complexity classes without machines: On complete languages for UP |series=Lecture Notes in Computer Science |volume=226 |doi=10.1007/3-540-16761-7_62 }}

= Efficiency issues =

Functional programming languages are typically less efficient in their use of CPU and memory than imperative languages such as C and Pascal.{{cite book |first=Larry C. |last=Paulson |author-link=Lawrence Paulson |title=ML for the Working Programmer|url=https://books.google.com/books?id=XppZdaDs7e0C|access-date=10 February 2013|date=28 June 1996|publisher=Cambridge University Press|isbn=978-0-521-56543-1}} This is related to the fact that some mutable data structures like arrays have a very straightforward implementation using present hardware. Flat arrays may be accessed very efficiently with deeply pipelined CPUs, prefetched efficiently through caches (with no complex pointer chasing), or handled with SIMD instructions. It is also not easy to create their equally efficient general-purpose immutable counterparts. For purely functional languages, the worst-case slowdown is logarithmic in the number of memory cells used, because mutable memory can be represented by a purely functional data structure with logarithmic access time (such as a balanced tree). However, such slowdowns are not universal. For programs that perform intensive numerical computations, functional languages such as OCaml and Clean are only slightly slower than C according to The Computer Language Benchmarks Game.{{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 |access-date=2011-06-20 |archive-url=https://web.archive.org/web/20130520162513/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 |archive-date=2013-05-20 |url-status=dead}} For programs that handle large matrices and multidimensional databases, array functional languages (such as J and 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.{{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 |s2cid=34527406}} Even if the involved copying that may seem implicit when dealing with persistent immutable data structures might seem computationally costly, some functional programming languages, like Clojure solve this issue by implementing mechanisms for safe memory sharing between formally immutable data.{{Cite web |title=An In-Depth Look at Clojure Collections |url=https://www.infoq.com/articles/in-depth-look-clojure-collections/ |access-date=2024-04-29 |website=InfoQ |language=en}} Rust distinguishes itself by its approach to data immutability which involves immutable references{{Cite web |title=References and Borrowing - The Rust Programming Language |url=https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html |access-date=2024-04-29 |website=doc.rust-lang.org}} and a concept called lifetimes.{{Cite web |title=Validating References with Lifetimes - The Rust Programming Language |url=https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html |access-date=2024-04-29 |website=doc.rust-lang.org}}

Immutable data with separation of identity and state and shared-nothing schemes can also potentially be more well-suited for concurrent and parallel programming by the virtue of reducing or eliminating the risk of certain concurrency hazards, since concurrent operations are usually atomic and this allows eliminating the need for locks. This is how for example java.util.concurrent classes are implemented, where some of them are immutable variants of the corresponding classes that are not suitable for concurrent use.{{Cite web |title=Concurrent Collections (The Java™ Tutorials > Essential Java Classes > Concurrency) |url=https://docs.oracle.com/javase/tutorial/essential/concurrency/collections.html |access-date=2024-04-29 |website=docs.oracle.com}} Functional programming languages often have a concurrency model that instead of shared state and synchronization, leverages message passing mechanisms (such as the actor model, where each actor is a container for state, behavior, child actors and a message queue).{{Cite web |date=2023-01-28 |title=Understanding The Actor Model To Build Non-blocking, High-throughput Distributed Systems - Scaleyourapp |url=https://scaleyourapp.com/actor-model/ |access-date=2024-04-29 |website=scaleyourapp.com |language=en-US}}{{Cite book |last1=Cesarini |first1=Francesco |title=Erlang programming: a concurrent approach to software development |last2=Thompson |first2=Simon |publisher=O'Reilly Media, Inc. |year=2009 |isbn=978-0-596-55585-6 |edition=1st |publication-date=2009-06-11 |page=6 |language=en}} This approach is common in Erlang/Elixir or Akka.

Lazy evaluation may also speed up the program, even asymptotically, whereas it may slow it down at most by a constant factor (however, it may introduce memory leaks if used improperly). Launchbury 1993 discusses theoretical issues related to memory leaks from lazy evaluation, and O'Sullivan et al. 2008{{cite web |url=http://book.realworldhaskell.org/read/profiling-and-optimization.html#x_eK1 |title=Chapter 25. Profiling and optimization |publisher=Book.realworldhaskell.org |access-date=2011-06-20}} 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}}.

== Abstraction cost ==

Some functional programming languages might not optimize abstractions such as higher order functions like "map" or "filter" as efficiently as the underlying imperative operations. Consider, as an example, the following two ways to check if 5 is an even number in Clojure:

(even? 5)

(.equals (mod 5 2) 0)

When benchmarked using the [https://clojars.org/criterium Criterium] tool on a Ryzen 7900X GNU/Linux PC in a Leiningen REPL 2.11.2, running on Java VM version 22 and Clojure version 1.11.1, the first implementation, which is implemented as:

{:added "1.0"

:static true}

[n] (if (integer? n)

(zero? (bit-and (clojure.lang.RT/uncheckedLongCast n) 1))

(throw (IllegalArgumentException. (str "Argument must be an integer: " n)))))

has the mean execution time of 4.76 ms, while the second one, in which .equals is a direct invocation of the underlying Java method, has a mean execution time of 2.8 μs – roughly 1700 times faster. Part of that can be attributed to the type checking and exception handling involved in the implementation of even?. For instance the [https://github.com/samber/lo lo library] for Go, which implements various higher-order functions common in functional programming languages using generics. In a benchmark provided by the library's author, calling map is 4% slower than an equivalent for loop and has the same allocation profile,{{Citation |last=Berthe |first=Samuel |title=samber/lo |date=2024-04-29 |url=https://github.com/samber/lo |access-date=2024-04-29}} which can be attributed to various compiler optimizations, such as inlining.{{Cite web |title=Go Wiki: Compiler And Runtime Optimizations - The Go Programming Language |url=https://go.dev/wiki/CompilerOptimizations |access-date=2024-04-29 |website=go.dev |language=en}}

One distinguishing feature of Rust are zero-cost abstractions. This means that using them imposes no additional runtime overhead. This is achieved thanks to the compiler using loop unrolling, where each iteration of a loop, be it imperative or using iterators, is converted into a standalone Assembly instruction, without the overhead of the loop controlling code. If an iterative operation writes to an array, the resulting array's elements will be stored in specific CPU registers, allowing for constant-time access at runtime.{{Cite web |title=Comparing Performance: Loops vs. Iterators - The Rust Programming Language |url=https://doc.rust-lang.org/book/ch13-04-performance.html |access-date=2024-04-29 |website=doc.rust-lang.org}}

= 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.{{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 |doi=10.1017/S0956796803004817 |s2cid=32346900 |accessdate=2006-05-28 |archivedate=2011-07-19 |archiveurl=https://web.archive.org/web/20110719201553/http://www.ub.utwente.nl/webdocs/ctit/1/00000084.pdf |url-status=deviated }}; {{cite web |title=Functional programming in Python, Part 3 |url=http://www-128.ibm.com/developerworks/linux/library/l-prog3.html |archive-url=https://web.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog3.html |archive-date=2007-10-16 |author=David Mertz |access-date=2006-09-17 |work=IBM developerWorks }}([https://web.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog.html Part 1], [https://web.archive.org/web/20071016124848/http://www-128.ibm.com/developerworks/linux/library/l-prog2.html Part 2]) For example, both D{{cite web |url=http://www.digitalmars.com/d/2.0/function.html#pure-functions |title=Functions — D Programming Language 2.0 |publisher=Digital Mars |date=30 December 2012}} and Fortran 95 explicitly support pure functions.

JavaScript, Lua,{{cite web|url=http://www.luafaq.org/#T1.2|title=Lua Unofficial FAQ (uFAQ)}} Python and Go{{Cite web|title=First-Class Functions in Go - The Go Programming Language|url=https://golang.org/doc/codewalk/functions/|access-date=2021-01-04|website=golang.org}} had first class functions from their inception.{{cite web|url=https://brendaneich.com/2008/04/popularity/|first=Brendan|last= Eich|title=Popularity|date=3 April 2008}} Python had support for "lambda", "map", "reduce", and "filter" in 1994, as well as closures in Python 2.2,{{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 |author-link=Guido van Rossum |date=2009-04-21 |access-date=2012-09-27}} though Python 3 relegated "reduce" to the functools standard library module.{{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 |access-date=2011-07-31}} First-class functions have been introduced into other mainstream languages such as Perl 5.0 in 1994, PHP 5.3, Visual Basic 9, C# 3.0, C++11, and Kotlin.{{citation needed|date=April 2015}}

In Perl, lambda, map, reduce, filter, and closures are fully supported and frequently used. The book Higher-Order Perl, released in 2005, was written to provide an expansive guide on using Perl for functional programming.

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

In Java, anonymous classes can sometimes be used to simulate closures;{{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}} however, anonymous classes are not always proper replacements to closures because they have more limited capabilities.{{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|access-date=11 May 2013|archive-url= https://web.archive.org/web/20130414180002/https://blogs.oracle.com/jag/entry/closures|archive-date=2013-04-14|url-status=dead}} Java 8 supports lambda expressions as a replacement for some anonymous classes.{{cite web|url=https://blogs.oracle.com/javatraining/entry/java_se_8_lambda_quick|title=Java SE 8 Lambda Quick Start|first=Michael|last=Williams|date=8 April 2013}}

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

Many object-oriented design patterns are expressible in functional programming terms: for example, the strategy pattern simply dictates use of a higher-order function, and the visitor pattern roughly corresponds to a catamorphism, or fold.

Similarly, the idea of immutable data from functional programming is often included in imperative programming languages,{{cite book |title=Effective Java |edition=Second |first=Joshua |last=Bloch |chapter=Item 15: Minimize Mutability |isbn=978-0321356680 |date=2008 |publisher=Addison-Wesley |url-access=registration |url=https://archive.org/details/effectivejava00bloc_0}} for example the tuple in Python, which is an immutable array, and Object.freeze() in JavaScript.{{Cite web|last=|first=|date=|title=Object.freeze() - JavaScript {{!}} MDN|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze|access-date=2021-01-04|website=developer.mozilla.org|quote=The Object.freeze() method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in.}}

Comparison to logic programming

Logic programming can be viewed as a generalisation of functional programming, in which functions are a special case of relations.{{cite book|author1=Daniel Friedman|author2=William Byrd|author3=Oleg Kiselyov|author4=Jason Hemann|title=The Reasoned Schemer, Second Edition|year=2018|publisher=The MIT Press}}

For example, the function, mother(X) = Y, (every X has only one mother Y) can be represented by the relation mother(X, Y). Whereas functions have a strict input-output pattern of arguments, relations can be queried with any pattern of inputs and outputs. Consider the following logic program:

mother(charles, elizabeth).

mother(harry, diana).

The program can be queried, like a functional program, to generate mothers from children:

?- mother(harry, X).

X = diana.

?- mother(charles, X).

X = elizabeth.

But it can also be queried backwards, to generate children:

?- mother(X, elizabeth).

X = charles.

?- mother(X, diana).

X = harry.

It can even be used to generate all instances of the mother relation:

?- mother(X, Y).

X = charles,

Y = elizabeth.

X = harry,

Y = diana.

Compared with relational syntax, functional syntax is a more compact notation for nested functions. For example, the definition of maternal grandmother in functional syntax can be written in the nested form:

maternal_grandmother(X) = mother(mother(X)).

The same definition in relational notation needs to be written in the unnested form:

maternal_grandmother(X, Y) :- mother(X, Z), mother(Z, Y).

Here :- means if and , means and.

However, the difference between the two representations is simply syntactic. In Ciao Prolog, relations can be nested, like functions in functional programming:A. Casas, D. Cabeza, M. V. Hermenegildo. A Syntactic Approach to

Combining Functional Notation, Lazy Evaluation and Higher-Order in

LP Systems. The 8th International Symposium on Functional and Logic

Programming (FLOPS'06), pages 142-162, April 2006.

grandparent(X) := parent(parent(X)).

parent(X) := mother(X).

parent(X) := father(X).

mother(charles) := elizabeth.

father(charles) := phillip.

mother(harry) := diana.

father(harry) := charles.

?- grandparent(X,Y).

X = harry,

Y = elizabeth.

X = harry,

Y = phillip.

Ciao transforms the function-like notation into relational form and executes the resulting logic program using the standard Prolog execution strategy.

Applications

= Text editors =

Emacs, a highly extensible text editor family uses its own Lisp dialect for writing plugins. The original author of the most popular Emacs implementation, GNU Emacs and Emacs Lisp, Richard Stallman considers Lisp one of his favorite programming languages.{{Cite web |title=How I do my Computing |url=https://stallman.org/stallman-computing.html |access-date=2024-04-29 |website=stallman.org}}

Helix, since version 24.03 supports previewing AST as S-expressions, which are also the core feature of the Lisp programming language family.{{Cite web |title=Helix |url=https://helix-editor.com/news/release-24-03-highlights/ |access-date=2024-04-29 |website=helix-editor.com}}

= Spreadsheets =

Spreadsheets can be considered a form of pure, zeroth-order, strict-evaluation functional programming system.{{cite journal|last1=Wakeling|first1=David|title=Spreadsheet functional programming|journal=Journal of Functional Programming|volume=17|issue=1|year=2007|pages=131–143|issn=0956-7968|doi=10.1017/S0956796806006186|s2cid=29429059|url=http://www.activemode.org/webroot/Workers/ActiveTraining/Programming/Pro_SpreadsheetFunctionalProgramming.pdf}} However, spreadsheets generally lack higher-order functions as well as code reuse, and in some implementations, also lack recursion. Several extensions have been developed for spreadsheet programs to enable higher-order and reusable functions, but so far remain primarily academic in nature.{{cite web |title=Improving the world's most popular functional language: user-defined functions in Excel |first1=Simon |last1=Peyton Jones |author-link1=Simon Peyton Jones |first2=Margaret |last2=Burnett|author2-link=Margaret Burnett |first3=Alan |last3=Blackwell |author-link3=Alan Blackwell |url=http://research.microsoft.com/~simonpj/Papers/excel/index.htm |date=March 2003 |archive-url=https://web.archive.org/web/20051016011341/http://research.microsoft.com/~simonpj/Papers/excel/index.htm |archive-date=2005-10-16}}

= Microservices =

Due to their composability, functional programming paradigms can be suitable for microservices-based architectures.{{Cite book |last=Rodger |first=Richard |title=The Tao of Microservices |date=11 December 2017 |publisher=Manning |isbn=9781638351733}}

= Academia =

Functional programming is an active area of research in the field of programming language theory. There are several peer-reviewed publication venues focusing on functional programming, including the International Conference on Functional Programming, the Journal of Functional Programming, and the Symposium on Trends in Functional Programming.

= Industry =

Functional programming has been employed in a wide range of industrial applications. For example, Erlang, which was developed by the Swedish company Ericsson in the late 1980s, was originally used to implement fault-tolerant telecommunications systems, but has since become popular for building a range of applications at companies such as Nortel, Facebook, Électricité de France and WhatsApp.{{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 |access-date=2009-08-29 |archive-url=https://web.archive.org/web/20091017070140/http://cufp.galois.com/2009/abstracts.html#ChristopherPiroEugeneLetuchy |archive-date=2009-10-17 |url-status=dead }}[http://blog.whatsapp.com/index.php/2012/01/1-million-is-so-2011/ 1 million is so 2011] {{Webarchive|url=https://web.archive.org/web/20140219234031/http://blog.whatsapp.com/index.php/2012/01/1-million-is-so-2011/ |date=2014-02-19}} // WhatsApp blog, 2012-01-06: "the last important piece of our infrastracture is Erlang" Scheme, a dialect of Lisp, was used as the basis for several applications on early Apple Macintosh computers and has been applied to problems such as training-simulation software and telescope control. OCaml, which was introduced in the mid-1990s, has seen commercial use in areas such as financial analysis, driver verification, industrial robot programming and static analysis of embedded software. Haskell, though initially intended as a research language, has also been applied in areas such as aerospace systems, hardware design and web programming.

Other functional programming languages that have seen use in industry include Scala,{{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 |access-date=2009-08-29 |archive-url=https://web.archive.org/web/20091017070140/http://cufp.galois.com/2009/abstracts.html#LeeMomtahan |archive-date=2009-10-17 |url-status=dead }} F#, Wolfram Language, Lisp,{{cite web |last=Graham |first=Paul |title=Beating the Averages |url=http://www.paulgraham.com/avg.html |year=2003 |access-date=2009-08-29}} Standard ML{{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 |access-date=2009-08-29}}{{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 |access-date=2009-08-29 |archivedate=2010-12-21 |archiveurl=https://web.archive.org/web/20101221110947/http://cufp.galois.com/2007/abstracts.html#VilleLaurikari |url-status=dead }} and Clojure.{{cite web |url=http://www.infoq.com/news/2009/01/clojure_production |last=Lorimer |first=R. J. |title=Live Production Clojure Application Announced |date=19 January 2009|work=InfoQ}} Scala has been widely used in Data science,{{Cite book |last=Bugnion |first=Pascal |title=Scala for Data Science |publisher=Packt |year=2016 |isbn=9781785281372 |edition=1st |language=en-US}} while ClojureScript,{{Cite web |title=Why developers like ClojureScript |url=https://stackshare.io/clojurescript |access-date=2024-04-29 |website=StackShare |language=en}} Elm{{Citation |last=Herrick |first=Justin |title=jah2488/elm-companies |date=2024-04-29 |url=https://github.com/jah2488/elm-companies |access-date=2024-04-29}} or PureScript{{Cite web |title=Why developers like PureScript |url=https://stackshare.io/purescript |access-date=2024-04-29 |website=StackShare |language=en}} are some of the functional frontend programming languages used in production. Elixir's Phoenix framework is also used by some relatively popular commercial projects, such as Font Awesome or Allegro (one of the biggest e-commerce platforms in Poland){{Cite web |last=Team |first=Editorial |date=2019-01-08 |title=ALLEGRO - all you need to know about the best Polish online marketplace |url=https://ecommercegermany.com/blog/allegro-all-you-need-to-know-about-the-best-polish-online-marketplace |access-date=2024-04-29 |website=E-commerce Germany News |language=en-US}}'s classified ads platform Allegro Lokalnie.{{Cite web |title=Websites using Phoenix Framework - Wappalyzer |url=https://www.wappalyzer.com/technologies/web-frameworks/phoenix-framework/ |access-date=2024-04-29 |website=www.wappalyzer.com}}

Functional "platforms" have been popular in finance for risk analytics (particularly with large investment banks). Risk factors are coded as functions that form interdependent graphs (categories) to measure correlations in market shifts, similar in manner to Gröbner basis optimizations but also for regulatory frameworks such as Comprehensive Capital Analysis and Review. Given the use of OCaml and Caml variations in finance, these systems are sometimes considered related to a categorical abstract machine. Functional programming is heavily influenced by category theory.{{Citation needed|date=August 2022}}

= Education =

Many universities teach functional programming.{{cite web|url=https://www.cs.ox.ac.uk/teaching/courses/2019-2020/fp/|title=Functional Programming: 2019-2020|publisher=University of Oxford Department of Computer Science|access-date=28 April 2020}}{{cite web|url=https://www.imperial.ac.uk/computing/current-students/courses/120_1/|title=Programming I (Haskell)|publisher=Imperial College London Department of Computing|access-date=28 April 2020}}{{cite web|url=https://www.nottingham.ac.uk/ugstudy/course/Computer-Science-BSc#yearsmodules|title=Computer Science BSc - Modules|access-date=28 April 2020}}{{cite book|last1=Abelson|first1=Hal|author-link1=Hal Abelson|last2=Sussman|first2=Gerald Jay|author-link2=Gerald Jay Sussman |title=Structure and Interpretation of Computer Programs |url=http://mitpress.mit.edu/sicp/ |year=1985|publisher=MIT Press|chapter=Preface to the Second Edition|edition=2|chapter-url=https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-6.html}} Some treat it as an introductory programming concept while others first teach imperative programming methods.{{cite web|url=https://cs61a.org/articles/about.html|title=Computer Science 61A, Berkeley|author=John DeNero|date=Fall 2019|publisher=Department of Electrical Engineering and Computer Sciences, Berkeley|access-date=2020-08-14}}

Outside of computer science, functional programming is used to teach problem-solving, algebraic and geometric concepts.{{Triangulation|196|Emmanuel Schanzer of Bootstrap}} It has also been used to teach classical mechanics, as in the book Structure and Interpretation of Classical Mechanics.

In particular, Scheme has been a relatively popular choice for teaching programming for years.{{Cite web |title=Why Scheme for Introductory Programming? |url=https://home.adelphi.edu/sbloch/class/pbd/testimonials/ |access-date=2024-04-29 |website=home.adelphi.edu}}{{Cite web |last=Staff |first=IMACS |date=2011-06-03 |title=What Is Scheme & Why Is it Beneficial for Students? |url=https://www.imacs.org/learn-computer-programming-using-scheme/ |access-date=2024-04-29 |website=IMACS – Making Better Thinkers for Life |language=en-US}}

See also

Notes and references

{{Notelist}}

{{Reflist

|refs =

{{cite journal |last=Clinger |first=Will |title=MultiTasking and MacScheme |journal=MacTech |volume=3 |issue=12 |year=1987 |url=http://www.mactech.com/articles/mactech/Vol.03/03.12/Multitasking/index.html |access-date=2008-08-28}}

{{cite journal |last=Hartheimer |first=Anne |title=Programming a Text Editor in MacScheme+Toolsmith |journal=MacTech |volume=3 |issue=1 |year=1987 |url=http://www.mactech.com/articles/mactech/Vol.03/03.1/SchemeWindows/index.html |access-date=2008-08-28 |url-status=dead |archive-url=https://web.archive.org/web/20110629183752/http://www.mactech.com/articles/mactech/Vol.03/03.1/SchemeWindows/index.html |archive-date=2011-06-29}}

{{cite conference |last=Kidd |first=Eric |url=http://cufp.galois.com/2007/abstracts.html#EricKidd |title=Terrorism Response Training in Scheme |conference=CUFP 2007 |access-date=2009-08-26 |archivedate=2010-12-21 |archiveurl=https://web.archive.org/web/20101221110947/http://cufp.galois.com/2007/abstracts.html#EricKidd |url-status=dead }}

{{cite conference |last=Cleis |first=Richard |url=http://cufp.galois.com/2006/abstracts.html#RichardCleis |title=Scheme in Space |conference=CUFP 2006 |access-date=2009-08-26 |archivedate=2010-05-27 |archiveurl=https://web.archive.org/web/20100527100429/http://cufp.galois.com/2006/abstracts.html#RichardCleis |url-status=dead }}

{{cite web |title=Who uses Erlang for product development? |work=Frequently asked questions about Erlang |url=http://erlang.org/faq/introduction.html#idp32582608 |access-date=2018-04-27}}

{{cite conference |last=Armstrong |first=Joe |title=Proceedings of the third ACM SIGPLAN conference on History of programming languages |chapter=A history of Erlang |conference=Third ACM SIGPLAN Conference on History of Programming Languages |location=San Diego, California |date=June 2007 |doi=10.1145/1238844.1238850 |isbn=9781595937667}}

{{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 |s2cid=524392 |doi-access=free}}

{{cite journal |last1=Minsky |first1=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 |date=July 2008 |doi=10.1017/S095679680800676X |doi-broken-date=1 November 2024 |s2cid=30955392 |doi-access=free }}

{{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 |access-date=2009-08-26 |archivedate=2011-10-08 |archiveurl=https://web.archive.org/web/20111008170929/http://cufp.galois.com/2007/slides/XavierLeroy.pdf |url-status=dead }}{{cite web |title=Haskell in industry |work=Haskell Wiki |url=http://www.haskell.org/haskellwiki/Haskell_in_industry |access-date=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.}}

{{cite web |title=Effective Scala |work=Scala Wiki |url=https://twitter.github.com/effectivescala/?sd |access-date=2012-02-21 |quote=Effective Scala. |archivedate=2012-06-19 |archiveurl=https://web.archive.org/web/20120619075044/http://twitter.github.com/effectivescala/?sd |url-status=deviated }}

{{cite web |title=Documentation for package java.util.function since Java 8 (also known as Java 1.8) |url=https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html |access-date=2021-06-16}}

{{cite web |title=State-Based Scripting in Uncharted 2 |url=http://www.gameenginebook.com/gdc09-statescripting-uncharted2.pdf |archive-url=https://web.archive.org/web/20121215014637/http://www.gameenginebook.com/gdc09-statescripting-uncharted2.pdf |archive-date=2012-12-15 |access-date=2011-08-08 |url-status=dead }}

{{cite conference |last1=Hudak |first1=Paul |last2=Hughes |first2=J. |last3=Jones |first3=S. P. |last4=Wadler |first4=P. |author-link1=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 |access-date=2013-09-26}}

{{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 |access-date=2011-06-20}}{{cite book |last=Chambers |first=John M. |author-link=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}}

{{cite web |website=Department of Applied Math |publisher=University of Colorado |title=Functional vs. Procedural Programming Language |url=http://amath.colorado.edu/computing/mmm/funcproc.html |archive-url=https://web.archive.org/web/20071113175801/http://amath.colorado.edu/computing/mmm/funcproc.html |archive-date=2007-11-13 |access-date=2006-08-28 |url-status=dead }}

{{cite web |url=http://fxsl.sourceforge.net/articles/FuncProg/Functional%20Programming.html |first=Dimitre |last=Novatchev |title=The Functional Programming Language XSLT — A proof through examples |access-date=May 27, 2006}}{{cite web |url=http://gnosis.cx/publish/programming/xml_models_fp.html |first=David |last=Mertz |title=XML Programming Paradigms (part four): Functional Programming approached to XML processing |access-date=May 27, 2006 |work=IBM developerWorks}}

{{cite journal |title=SEQUEL: A structured English query language |first1=Donald D. |last1=Chamberlin |author-link1=Donald D. Chamberlin |first2=Raymond F. |last2=Boyce |author-link2=Raymond F. Boyce |journal=Proceedings of the 1974 ACM SIGFIDET |pages=249–264 |year=1974}}{{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 |access-date=2011-11-08 |archive-date=2013-09-17 |archive-url=https://web.archive.org/web/20130917092159/http://research.edf.com/research-and-the-scientific-community/software/sim-diasca-80704.html |url-status=dead }}

{{cite web |url=http://www.codecommit.com/blog/scala/implementing-persistent-vectors-in-scala |first=Daniel |last=Spiewak |title=Implementing Persistent Vectors in Scala |date=26 August 2008 |website=Code Commit |access-date=17 April 2012 |archivedate=23 September 2015 |archiveurl=https://web.archive.org/web/20150923205254/http://www.codecommit.com/blog/scala/implementing-persistent-vectors-in-scala |url-status=deviated }}

}}

Further reading

  • {{cite book |last1=Abelson |first1=Hal |author-link1=Hal Abelson |last2=Sussman |first2=Gerald Jay |author-link2=Gerald Jay Sussman |title=Structure and Interpretation of Computer Programs |url=https://mitpress.mit.edu/9780262510363/structure-and-interpretation-of-computer-programs/ |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 |author-link1=Haskell Curry |author-link2=J. Roger Hindley |author-link3=Jonathan P. Seldin |title=Combinatory Logic |volume=II |year=1972 |publisher=North Holland |location=Amsterdam |isbn=978-0-7204-2208-5}}
  • 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=2018|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=Michaelson |first1=Greg |title=An Introduction to Functional Programming Through Lambda Calculus |date=10 April 2013 |publisher=Courier Corporation |isbn=978-0-486-28029-5 |language=en}}
  • {{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 Victor 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|date=2011-08-25}}

  • {{cite web

| last=Ford

| first=Neal

| title=Functional thinking

| access-date=2021-11-10

| url=http://nealford.com/functionalthinking.html

}}

  • {{cite web

| last=Akhmechet

| first=Slava

| title=defmacro – Functional Programming For The Rest of Us

| access-date=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 paradigms navbox}}

{{Types of programming languages}}

{{Authority control}}

{{DEFAULTSORT:Functional programming}}

Category:Programming paradigms

Category:Articles with example C code