functional programming for subroutineoriented programming see procedural programming programming paradigms action agentoriented arrayoriented automatabased concurrent computing relativistic programming datadriven declarative contrast imperative functional functional logic purely functional logic abductive logic answer set concurrent logic functional logic inductive logic constraint constraint logic concurrent constraint logic dataflow flowbased reactive dynamicscripting eventdriven functionlevel contrast valuelevel pointfree style concatenative generic imperative contrast declarative procedural objectoriented literate languageoriented naturallanguage programming disciplinespecific domainspecific grammaroriented intentional metaprogramming automatic inductive programming reflective attributeoriented macro template nonstructured contrast structured array nondeterministic parallel computing processoriented probabilistic stackbased structured contrast nonstructured blockstructured objectoriented actorbased classbased concurrent prototypebased by separation of concerns aspectoriented roleoriented subjectoriented recursive symbolic valuelevel contrast functionlevel quantum programming vte in computer science functional programming is a programming paradigma style of building the structure and elements of computer programsthat treats computation as the evaluation of mathematical functions and avoids changingstate and mutable data it is a declarative programming paradigm which means programming is done with expressions or declarations instead of statements in functional code the output value of a function depends only on the arguments that are passed to the function so calling a function f twice with the same value for an argument x produces the same result fx each time this is in contrast to procedures depending on a local or global state which may produce different results at different times when called with the same arguments but a different program state eliminating side effects ie 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 languages can be viewed as elaborations on the lambda calculus another wellknown declarative programming paradigm logic programming is based on relations in contrast imperative programming changes state with commands in the source code the simplest example being assignment imperative programming does have subroutine functions but these are not functions in the mathematical sense they can have side effects that may change the value of program state functions without return values therefore make sense because of this they lack referential transparency ie the same language expression can result in different values at different times depending on the state of the executing program functional programming languages have largely been emphasized in academia rather than in commercial software development however prominent programming languages that support functional programming such as common lisp scheme 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 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 it is a mathematical abstraction rather than a programming languagebut it forms the basis of almost all current functional programming languages an equivalent theoretical formulation combinatory logic is commonly perceived as more abstract than lambda calculus and preceded it in invention combinatory logic and lambda calculus were both originally developed to achieve a clearer approach to the foundations of mathematics an early functionalflavored language was lisp developed in the late 1950s for the ibm 7007000 series scientific computers by john mccarthy while at massachusetts institute of technology mit information processing language ipl is sometimes cited as the first computerbased functional programming language it is an assemblystyle 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 assemblylevel language code can be data so ipl can be regarded as having higherorder functions however it relies heavily on mutating list structure and similar imperative features kenneth e iverson developed apl in the early 1960s described in his 1962 book a programming language isbn9780471430148 apl was the primary influence on john backuss fp in the early 1990s iverson and roger hui created j in the mid1990s arthur whitney who had previously worked with iverson created k which is used commercially in financial industries along with its descendant q 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 backuss paper popularized research into functional programming though it emphasized functionlevel programming rather than the lambdacalculus 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 ml eventually developed into several dialects the most common of which are now ocaml and standard ml meanwhile the development of scheme a simple lexically scoped and impurely functional dialect of lisp as described in the influential lambda papers and the classic 1985 textbook structure and interpretation of computer programs brought awareness of the power of functional programming to the wider programminglanguages community in the 1980s per martinlf 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 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 since 1990 more recently it has found use in niches such as parametric cad courtesy of the openscad language built on the csg geometry framework although its inability to reassign values has led to much confusion among users who are often unfamiliar with functional programming as a concept functional programming continues to be used in commercial settings concepts a number of concepts and paradigms are specific to functional programming and generally foreign to imperative programming including objectoriented programming however programming languages often cater to several programming paradigms so programmers using mostly imperative languages may have utilized some of these concepts firstclass and higherorder functions firstclass function and higherorder function higherorder functions are functions that can either take other functions as arguments or return them as results in calculus an example of a higherorder function is the differential operator d d x displaystyle ddx which returns the derivative of a function f displaystyle f higherorder functions are closely related to firstclass functions in that higherorder functions and firstclass functions both allow functions as arguments and results of other functions the distinction between the two is subtle higherorder describes a mathematical concept of functions that operate on other functions while firstclass is a computer science term that describes programming language entities that have no restriction on their use thus firstclass functions can appear anywhere in the program that other firstclass entities like numbers can including as arguments to other functions and as their return values higherorder 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 pure functions or expressions have no side effects memory or io 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 sideeffects the result is constant with respect to that argument list sometimes called referential transparency ie if calling the pure function again with the same arguments returns the same result this can enable caching optimizations such as memoization if there is no data dependency between two pure expressions their order can be reversed or they can be performed in parallel and they cannot interfere with one another in other terms the evaluation of any pure expression is threadsafe if the entire language does not allow sideeffects 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 commonsubexpression elimination for pure function calls they cannot always do this for precompiled 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 c11 added constexpr keyword with similar semantics recursion 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 although some recursion requires maintaining a stack tail recursion can be recognized and optimized by a compiler into the same code used to implement iteration in imperative languages the scheme language standard requires implementations to recognize and optimize tail recursion tail recursion optimization can be implemented by transforming the program into continuation passing style during compiling among other approaches common patterns of recursion can be factored out using higher order functions with catamorphisms and anamorphisms or folds and unfolds being the most obvious examples such higher order functions play a role analogous to builtin 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 languages type system some special purpose languages such as coq allow only wellfounded 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 wellfounded recursion with a few other constraints is called total functional programming strict versus nonstrict evaluation evaluation strategy functional languages can be categorized by whether they use strict eager or nonstrict 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 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 ie 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 lazy evaluation is used by default in several pure functional languages including miranda clean and haskell hughes 1984 argues for lazy evaluation as a mechanism for improving program modularity through separation of concerns by easing independent implementation of producers and consumers of data streams type systems especially since the development of hindleymilner 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 though 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 compiletime type checking makes programs more reliable in absence of other reliability techniques like testdriven development while type inference frees the programmer from the need to manually declare types to the compiler in most cases some researchoriented 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 a limited form of dependent types called generalized algebraic data types gadts can be implemented in a way that provides some of the benefits of dependently typed programming while avoiding most of its inconvenience referential transparency 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 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 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 int plusoneint x return x1 is transparent as it does not implicitly change the input x and thus has no such side effects functional programs exclusively use this type of function and are therefore referentially transparent functional programming in nonfunctional languages it is possible to use a functional style of programming in languages that are not traditionally considered functional languages explicitly support pure functions javascript lua 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 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 objectoriented design patterns are expressible in functional programming terms for example the strategy pattern simply dictates use of a higherorder 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 for example the tuple in python which is an immutable array data structures purely functional data structure purely functional data structures are often represented in a different way than their imperative counterparts 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 io pure functional programming completely prevents sideeffects and provides referential transparency higherorder 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 higherorder 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 io 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 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 io 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 eg when asked to define new monads which is sometimes needed for certain types of libraries 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 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 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 efficiency issues functional programming languages are typically less efficient in their use of cpu and memory than imperative languages such as c and pascal 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 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 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 multilevel caches where a cache miss may cost hundreds of cycles coding styles 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 numbers php printing first 10 fibonacci numbers using function function fibint n int return n 0 n 1 n fibn 1 fibn 2 for i 0 i 10 i echo fibi phpeol printing first 10 fibonacci numbers using closure fib functionint n usefib int return n 0 n 1 n fibn 1 fibn 2 for i 0 i 10 i echo fibi phpeol printing a list with first 10 fibonacci numbers with generators function fibint n yield 0 n yield 1 n second first 2 1 while n 0 yield first fibo fib10 foreach fibo as value echo value phpeol python printing first 10 fibonacci numbers iterative def fibonaccin first0 second1 for in rangen printfirst sideeffect first second second first second assignment fibonacci10 printing first 10 fibonacci numbers functional expression style fibonacci lambda n first0 second1 if n 0 else strfirst n fibonaccin 1 second first second printfibonacci10 end printing a list with first 10 fibonacci numbers with generators def fibonaccin first0 second1 for in rangen yield first first second second first second assignment printlistfibonacci10 printing a list with first 10 fibonacci numbers functional expression style fibonacci lambda n first0 second1 if n 0 else fibonaccin 1 second first second printfibonacci10 printing first 10 fibonacci numbers recursive style def fibonaccin if n 1 return n else return fibonaccin2 fibonaccin1 for n in range10 printfibonaccin haskell printing first 10 fibonacci numbers functional expression style fibonacciaux n first second if n 0 then else show first n fibonacciaux n 1 second first second fibonacci n fibonacciaux n 0 1 main putstr fibonacci 10 printing a list with first 10 fibonacci numbers functional expression style fibonacciaux n first second if n 0 then else fibonacciaux n 1 second first second fibonacci n fibonacciaux n 0 1 main putstrln show fibonacci 10 printing the 11th fibonacci number functional expression style fibonacci n if n 0 then 0 else if n 1 then 1 else fibonaccin 1 fibonaccin 2 main putstrln show fibonacci 10 printing the 11th fibonacci number functional expression style tail recursive fibonacciaux n first second if n 0 then first else fibonacciaux n 1 second first second fibonacci n fibonacciaux n 0 1 main putstrln show fibonacci 10 printing the 11th fibonacci number functional expression style with recursive lists fibonacciaux first second first fibonacciaux second first second select n zs if n0 then head zs else select n 1 tail zs fibonacci n select n fibonacciaux 0 1 main putstrln show fibonacci 10 printing the 11th fibonacci number functional expression style with primitives for recursive lists fibonacciaux first second first fibonacciaux second first second fibonacci n fibonacciaux 0 1 n main putstrln show fibonacci 10 printing the 11th fibonacci number functional expression style with primitives for recursive lists more concisely fibonacciaux 01zipwith fibonacciaux tail fibonacciaux fibonacci n fibonacciaux n main putstrln show fibonacci 10 printing the 11th fibonacci number functional declaration style fibonacci 0 0 fibonacci 1 1 fibonacci n fibonacci n1 fibonacci n2 main putstrln show fibonacci 10 printing the 11th fibonacci number functional declaration style tail recursive fibonacciaux 0 first first fibonacciaux n first second fibonacciaux n 1 second first second fibonacci n fibonacciaux n 0 1 main putstrln show fibonacci 10 printing the 11th fibonacci number functional declaration style using lazy infinite lists and primitivesfibs 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 printing the first 10 fibonacci numbers list comprehension generator style fibs main putstrln show take 10 fibs 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 welltyped recursive version the type constraints are optional through signature pattern matching define constraints that are common to all candidates proto fib uintd n uintd multi fib 0 0 multi fib 1 1 multi fib n fibn 1 fibn 2 for 10 n say fibn an alternative to this is to construct a lazy iterative sequence which appears as an almost direct illustration of the sequence my fib 0 1 each additional entry is the sum of the previous two and this sequence extends lazily indefinitely say fib display the first 10 entries erlang erlang is a functional concurrent generalpurpose programming language a fibonacci algorithm implemented in erlang note this is only for demonstrating the erlang syntax use other algorithms for fast performance modulefib this is the file fiberl the module and the filename must match export this exports the function fib of arity 1 fib1 1 if 1 then return 1 otherwise note the semicolon meaning else fib2 1 if 2 then return 1 otherwise fibn fibn 2 fibn 1 elixir elixir is a functional concurrent generalpurpose programming language that runs on the erlang virtual machine beam the fibonacci function can be written in elixir as followsdefmodule fibonacci do def fib0 do 0 def fib1 do 1 def fibn do fibn1 fibn2 end lisp the fibonacci function can be written in common lisp as follows defun fib n optional a 0 b 1 if n 0 a fib n 1 b a b or defun fib n if or n 0 n 1 n fib n 1 fib n 2 the program can then be called as fib 10 clojure the fibonacci function can be written in clojure as follows defn fib loop if zero i a recur b a b dec i the program can then be called as fib 7 explicitly using lazyseq the infinite sequence of fibonacci numbers can be defined recursively lazy infinite sequence def fibs cons 0 cons 1 lazyseq map fibs rest fibs list of first 10 fibonacci numbers taken from infinite sequence take 10 fibs kotlin the fibonacci function can be written in kotlin as follows fun fibx int int if x in 01 x else fibx 1 fibx 2 the program can then be called as fib7 swift the fibonacci function can be written in swift as followsfunc fib x int int if x 0 x 1 return x else return fibx 1 fibx 2 the function can then be called asfib7 javascript the fibonacci function can be written in javascript as follows const fib x x 0 x 1 x fibx 1 fibx 2 sequencel sequencel is a functional concurrent generalpurpose programming language the fibonacci function can be written in sequencel as follows fibn n when n 2 else fibn 1 fibn 2 the function can then be called as fib10 to reduce the memory consumed by the call stack when computing a large fibonacci term a tailrecursive version can be used a tailrecursive function is implemented by the sequencel compiler as a memoryefficient looping structure fibn fibhelper0 1 n fibhelperprev next n prev when n 1 else next when n 1 else fibhelpernext next prev n 1 ruby the fibonacci function can be written in ruby using lambdas as follows fib n n 0 n 1 n fib tcl the fibonacci function can be written in tcl as a recursive function as follows proc fibo x expr x2 x scala the fibonacci function can be written in scala in several ways imperative java style def fibimpn int int var i 0 var j 1 for k 0 until n val l i j i j j l i recursive style slow def fibrecn int int n match case 0 0 case 1 1 case fibrecn 1 fibrecn 2 recursive style with tail call optimization fast def fibtailrecn int int tailrec def fiba int b int c int int if a 0 0 else if a 2 c else fiba 1 c b c fibn 0 1 using scala streams val fibstream stream 0 1 fibstream zip fibstreamtailmapn n1 n2 use in industry functional programming has long been popular in academia but with few industrial applications other functional programming languages that have seen use in industry include scala in education functional programming is being used as a method to teach problem solving algebra and geometric concepts it has also been used as a tool to teach classical mechanics in structure and interpretation of classical mechanics computer programming portal purely functional programming comparison of programming paradigms eager evaluation list of functional programming topics nested function inductive functional programming functional reactive programming abelson hal sussman gerald jay 1985 structure and interpretation of computer programs 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 northholland publishing company amsterdam 1958 curry haskell b hindley j roger seldin jonathan p 1972 combinatory logic vol ii amsterdam north holland isbn0720422086 dominus mark jason higherorder perl morgan kaufmann 2005 felleisen matthias findler robert flatt matthew krishnamurthi shriram 2001 how to design programs mit press graham paul ansi common lisp englewood cliffs new jersey prentice hall 1996 maclennan bruce j functional programming practice and theory addisonwesley 1990 osullivan brian stewart don goerzen john 2008 real world haskell oreilly 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 addisonwesley longman limited 1996 listen to this article infodl this audio file was created from a revision of the article functional programming dated 20110825 and does not reflect subsequent edits to the article audio help more spoken articles ford neal 20120129 functional thinking why functional programming is on the rise retrieved 20130224 akhmechet slava 20060619 defmacro functional programming for the rest of us retrieved 20130224 an introduction functional programming in python by david mertz part 1 part 2 part 3 vtetypes of programming languages actorbased array aspectoriented classbased concatenative concurrent dataflow declarative domainspecific dynamic esoteric eventdriven extensible functional imperative logic macro metaprogramming multiparadigm objectbased objectoriented pipeline procedural prototypebased reflective rulebased scripting stack based synchronous templating assembly compiled interpreted machine lowlevel highlevel very highlevel first generation second generation third generation fourth generation fifth generation nonenglishbased visual authority control bne xx547935 bnf cb121910539 data gnd 41987408 lccn sh87007844 